<?php

class ContractsController extends Zend_Controller_Action
{
    function preDispatch()
    {
		if(!$_SESSION['identity'])
        {
            $this->_redirect("/login");
        }
		
         //Make menu
         $mod_menu = new Db_Tables2_BDictMenu();
         $this->view->main_menu = $mod_menu->MenuDecolation();
        
        $mod_params = new Db_Tables2_BDictParams();
        $this->view->sys_name = $mod_params->GetSysName();
    }
	
    function indexAction()
    {
		$params = $this->_request->getParams();
		
		$this->view->title = "合同列表";
		
		$mod_t_area = new Db_Tables2_TArea();
		$this->view->provinces = $mod_t_area->GetProvinces();
		
		$sales_role_id = array();
		
		$mod_params = new Db_Tables2_BDictParams();
		$sales_role_id[] = $mod_params->GetVal("LEVEL-1");
		$sales_role_id[] = $mod_params->GetVal("LEVEL-2");
		
		$mod_user = new Db_Tables2_User();
		$sales = $mod_user->GetUsersByRole($sales_role_id);
		
		if("LEVEL-2" == $_SESSION['identity']['level']) //销售主管只可以看属于自己的员工合同
		{
			$mod_user = new Db_Tables2_User();
			$my_staff_ids = $mod_user->GetMyStaffIds($_SESSION['identity']['userid']);
			
			foreach($sales as $sid => $sname)
			{
				if(!in_array($sid, $my_staff_ids))
				{
					unset($sales[$sid]);
				}
			}
		}
		
		$this->view->sales = $sales;
		
		$mod_owners = new Db_Tables2_BOwner();
		$this->view->owners = $mod_owners->GetOwners();
		
		$mod_products = new Db_Tables2_BDictProduct();
		$this->view->products = $mod_products->GetProducts(0);
		
		$mod_statuses = new Db_Tables2_BDictContractStatus();
		$this->view->statuses = $mod_statuses->GetStatuses();
		
		$params_pool = array();
		$mod_tables = new Db_Joins_TablesJoins();
    	
		if($params['contract_type_id'])
    	{
    		$mod_tables->contract_type_id = $params['contract_type_id'];
    		$this->view->contract_type_id = $params['contract_type_id'];
    		$params_pool[] = "contract_type_id=".$params['contract_type_id'];
    	}
    	
		if($params['pay_type'])
    	{
    		$mod_tables->pay_type = $params['pay_type'];
    		$this->view->pay_type = $params['pay_type'];
    		$params_pool[] = "pay_type=".$params['pay_type'];
    	}
    	
		if($params['start_date_start'])
    	{
    		$mod_tables->start_date_start = $params['start_date_start'];
    		$this->view->start_date_start = $params['start_date_start'];
    		$params_pool[] = "start_date_start=".$params['start_date_start'];
    	}
    	
		if($params['start_date_end'])
    	{
    		$mod_tables->start_date_end = $params['start_date_end'];
    		$this->view->start_date_end = $params['start_date_end'];
    		$params_pool[] = "start_date_end=".$params['start_date_end'];
    	}
    	
		if($params['date_start'])
    	{
    		$mod_tables->date_start = $params['date_start'];
    		$this->view->date_start = $params['date_start'];
    		$params_pool[] = "date_start=".$params['date_start'];
    	}
    	
		if($params['date_end'])
    	{
    		$mod_tables->date_end = $params['date_end'];
    		$this->view->date_end = $params['date_end'];
    		$params_pool[] = "date_end=".$params['date_end'];
    	}
		
		if($params['expired_date_start'])
    	{
    		$mod_tables->expired_date_start = $params['expired_date_start'];
    		$this->view->expired_date_start = $params['expired_date_start'];
    		$params_pool[] = "expired_date_start=".$params['expired_date_start'];
    	}
		
		if($params['expired_date_end'])
    	{
    		$mod_tables->expired_date_end = $params['expired_date_end'];
    		$this->view->expired_date_end = $params['expired_date_end'];
    		$params_pool[] = "expired_date_end=".$params['expired_date_end'];
    	}
		
		if($params['sales_emp_id'] && "LEVEL-1" != $_SESSION['identity']['level'])
    	{
    		$mod_tables->sales_emp_id = $params['sales_emp_id'];
    		$this->view->sales_emp_id = $params['sales_emp_id'];
    		$params_pool[] = "sales_emp_id=".$params['sales_emp_id'];
    	}elseif("LEVEL-1" == $_SESSION['identity']['level']) //销售只可以看自己
		{
			$mod_tables->sales_emp_id = $_SESSION['identity']['userid'];
		}
		
		if($params['owner_id'])
    	{
    		$mod_tables->owner_id = $params['owner_id'];
    		$this->view->owner_id = $params['owner_id'];
    		$params_pool[] = "owner_id=".$params['owner_id'];
    	}
		
		if($params['product_id'])
    	{
    		$mod_tables->product_id = $params['product_id'];
    		$this->view->product_id = $params['product_id'];
    		$params_pool[] = "product_id=".$params['product_id'];
    	}
		
		if($params['contract_type'])
    	{
    		$mod_tables->contract_type = $params['contract_type'];
    		$this->view->contract_type = $params['contract_type'];
    		$params_pool[] = "contract_type=".$params['contract_type'];
    	}
		
		if($params['renew_type'])
    	{
    		$mod_tables->renew_type = $params['renew_type'];
    		$this->view->renew_type = $params['renew_type'];
    		$params_pool[] = "renew_type=".$params['renew_type'];
    	}
		
    	if($params['provinceId'])
    	{
    		$mod_tables->provinceId = $params['provinceId'];
    		$this->view->provinceId = $params['provinceId'];
    		$params_pool[] = "provinceId=".$params['provinceId'];
			
			$this->view->init_cities = $mod_t_area->GetCities($params['provinceId']);
    	}
    	
    	if($params['cityId'])
    	{
    		$mod_tables->cityId = $params['cityId'];
    		$this->view->cityId = $params['cityId'];
    		$params_pool[] = "cityId=".$params['cityId'];
    	}
		
		if(is_numeric($params['status']))
    	{
			$mod_tables->status = $params['status'];
    		$this->view->status = $params['status'];
    		$params_pool[] = "status=".$params['status'];
    	}
		
		if($params['keyword'])
    	{
    		$mod_tables->keyword = $params['keyword'];
    		$this->view->keyword = $params['keyword'];
    		$params_pool[] = "keyword=".$params['keyword'];
    	}
		
		if(!$params['page_id'])
    	{
    		$page_id = 1;
    	}else{
    		$page_id = $params['page_id'];
    	}
    	
    	if($page_id)
    	{
    		$mod_tables->page_id = $page_id;
    		$this->view->page_id = $page_id;
    	}
		
		if($params['via'])
		{
			$mod_tables->via = $params['via'];
		}
		
		$this->view->data = $result = $mod_tables->GetContracts();
		
//		if($params['msg'])
//		{
//			$ext = new Sys_Extensions();
//			$ext->FormatArray($this->view->data);
//			die;
//		}
		
		//make pagination
    	if(!empty($params_pool))
    	{
    		$params_string = implode("&", $params_pool);
    	}else{
    		$params_string = "";
    	}
    	
    	if(1 == $page_id)
    	{
    		$first_page_string = "";
    		$previous_page_string = "";
    	}else{
    		$first_page_string = "<a href='?page_id=1&".$params_string."'>最前页</a>&nbsp;&nbsp;&nbsp;";
    		$previous_page_string = "<a href='?page_id=".($page_id-1)."&".$params_string."'>上一页</a>&nbsp;&nbsp;&nbsp;";
    	}
    	
    	if($page_id < $result['total_pages'] )
    	{
    		$next_page_string = "<a href='?page_id=".($page_id+1)."&".$params_string."'>下一页</a>&nbsp;&nbsp;&nbsp;";
    		$last_page_string = "<a href='?page_id=".$result['total_pages']."&".$params_string."'>最后页</a>&nbsp;&nbsp;&nbsp;";
    	}else{
    		$next_page_string = "";
    		$last_page_string = "";
    	}
    	
		$this->view->params_string = $params_string;
    	$this->view->pagination = $first_page_string.$previous_page_string.$next_page_string.$last_page_string;
        $this->view->export_link = "/contracts/index-export?".$params_string;
        $this->view->export_link2 = "/contracts/index-export2?".$params_string;
		
		if($params['msg'])
		{
				switch ($params['msg'])
				{
					case 1:
						$this->view->msg = "您已成功申请合同，请等待审核。";
						break;
					case 2:
						$this->view->msg = "状态更改成功";
						break;
					case 3:
						$this->view->msg = "状态更改失败";
						break;
					case 4:
						$this->view->msg = "关键参数缺失";
						break;
					case 5:
						$this->view->msg = "您无修改此合同的权限";
						break;
					case 6:
						$this->view->msg = "找不到此合同";
						break;
					case 7:
						$this->view->msg = "您已成功编辑合同，请等待审核。";
						break;
					case 8:
						$this->view->msg = "该合同不满足开票标准";
						break;
					case 9:
						$this->view->msg = "必须合同发起人才可以开票";
						break;
					case 10:
						$this->view->msg = "开票由于异常原因导致失败，请联系管理员";
						break;
					case 11:
						$this->view->msg = "开票申请成功，请等待财务执行";
						break;
					case 12:
						$this->view->msg = "找不到此开票申请";
						break;
				}
		}
	}

    public function indexExportAction()
    {
        $params = $this->_request->getParams();
        $objPHPExcel = new PHPExcel();
		$mod_contract = new Db_Tables2_BContract();
		$mod_logs_contract = new Db_Tables2_BLogsContract();
		
		$dealers_db = Zend_Registry::get("dealers_db");
		$select = $dealers_db->select();
		$select->from("b_bu_auth", "*");
		$select->where("emp_id = ?", $_SESSION['identity']['userid']);
		$row = $dealers_db->fetchRow($select);

		$mod_reports = new Db_Joins_ReportsJoins();
		$mod_reports->skip_pagination = 1;
		$mod_reports->emp_auth_row = $row;
    	
		if($params['start_date_start'])
		{
			$mod_reports->start_date_start = $params['start_date_start'];
		}
    	
		if($params['start_date_end'])
		{
			$mod_reports->start_date_end = $params['start_date_end'];
		}
    	
		if($params['expired_date_start'])
		{
			$mod_reports->expired_date_start = $params['expired_date_start'];
		}
    	
		if($params['expired_date_end'])
		{
			$mod_reports->expired_date_end = $params['expired_date_end'];
		}
    	
		if($params['keyword'])
    	{
    		$mod_reports->keyword = $params['keyword'];
    	}
		
		if($params['group_id'])
    	{
    		$mod_reports->group_id = $params['group_id'];
    	}
		
		if($params['factory_id'])
    	{
    		$mod_reports->factory_id = $params['factory_id'];
    	}
		
		if($params['product_id'])
    	{
    		$mod_reports->product_id = $params['product_id'];
    	}
		
		if($params['provinceId'])
    	{
    		$mod_reports->province_id = $params['provinceId'];
    	}
		
		if($params['cityId'])
    	{
    		$mod_reports->city_id = $params['cityId'];
    	}
		
		if($params['sort_type'])
    	{
    		$mod_reports->sort_type = $params['sort_type'];
		}else{
			$mod_reports->sort_type = 1;
		}
		
		if(!$params['page_id'])
    	{
    		$page_id = 1;
    	}else{
    		$page_id = $params['page_id'];
    	}
    	
    	if($page_id)
    	{
    		$mod_reports->page_id = $page_id;
    		$this->view->page_id = $page_id;
    	}
		
		$result = $mod_reports->ContractExport1();
		
        $result = $result['current_page_info'];

        if(!empty($result))
        {
			$mod_ext = new Sys_Extensions();
			$columns = $mod_ext->ExcelColumnHeadGeneration(200);
			
			$column_ct = 0;
			
            //title
            $objPHPExcel->setActiveSheetIndex(0)->setCellValue($columns[$column_ct].'1', '合同编号');
			$column_ct += 1;
            $objPHPExcel->setActiveSheetIndex(0)->setCellValue($columns[$column_ct].'1', '产品');
			$column_ct += 1;
            $objPHPExcel->setActiveSheetIndex(0)->setCellValue($columns[$column_ct].'1', '签约日期');
			$column_ct += 1;
            $objPHPExcel->setActiveSheetIndex(0)->setCellValue($columns[$column_ct].'1', '城市');
			$column_ct += 1;
            $objPHPExcel->setActiveSheetIndex(0)->setCellValue($columns[$column_ct].'1', '销售');
			$column_ct += 1;
            $objPHPExcel->setActiveSheetIndex(0)->setCellValue($columns[$column_ct].'1', '品牌');
			$column_ct += 1;
            $objPHPExcel->setActiveSheetIndex(0)->setCellValue($columns[$column_ct].'1', '厂商');
			$column_ct += 1;
            $objPHPExcel->setActiveSheetIndex(0)->setCellValue($columns[$column_ct].'1', '城市');
			$column_ct += 1;
            $objPHPExcel->setActiveSheetIndex(0)->setCellValue($columns[$column_ct].'1', '付款方式');
            $column_ct += 1;
            $objPHPExcel->setActiveSheetIndex(0)->setCellValue($columns[$column_ct].'1', '客户名称');
			$column_ct += 1;
            $objPHPExcel->setActiveSheetIndex(0)->setCellValue($columns[$column_ct].'1', '签约公司');
			$column_ct += 1;
            $objPHPExcel->setActiveSheetIndex(0)->setCellValue($columns[$column_ct].'1', '经销商ID');
			$column_ct += 1;
            $objPHPExcel->setActiveSheetIndex(0)->setCellValue($columns[$column_ct].'1', '签约性质');
			$column_ct += 1;
            $objPHPExcel->setActiveSheetIndex(0)->setCellValue($columns[$column_ct].'1', '客户性质');
			$column_ct += 1;
            $objPHPExcel->setActiveSheetIndex(0)->setCellValue($columns[$column_ct].'1', '乙方单位');
			$column_ct += 1;
            $objPHPExcel->setActiveSheetIndex(0)->setCellValue($columns[$column_ct].'1', '合同起期');
			$column_ct += 1;
            $objPHPExcel->setActiveSheetIndex(0)->setCellValue($columns[$column_ct].'1', '合同止期');
			$column_ct += 1;
            $objPHPExcel->setActiveSheetIndex(0)->setCellValue($columns[$column_ct].'1', '回款日期');
			$column_ct += 1;
            $objPHPExcel->setActiveSheetIndex(0)->setCellValue($columns[$column_ct].'1', '合同金额');
			$column_ct += 1;
            $objPHPExcel->setActiveSheetIndex(0)->setCellValue($columns[$column_ct].'1', '回款金额');
			$column_ct += 1;
            $objPHPExcel->setActiveSheetIndex(0)->setCellValue($columns[$column_ct].'1', '审批状态');
            $column_ct += 1;
            $objPHPExcel->setActiveSheetIndex(0)->setCellValue($columns[$column_ct].'1', '备注');
            $column_ct += 1;
            $objPHPExcel->setActiveSheetIndex(0)->setCellValue($columns[$column_ct].'1', '合同类型');
            $column_ct += 1;

			if($params['product_id'])
			{
				switch($params['product_id'])
				{
					case 1:
						$objPHPExcel->setActiveSheetIndex(0)->setCellValue($columns[$column_ct].'1', '签约平台数量');
						$column_ct += 1;
						$objPHPExcel->setActiveSheetIndex(0)->setCellValue($columns[$column_ct].'1', '服务平台1');
						$column_ct += 1;
						$objPHPExcel->setActiveSheetIndex(0)->setCellValue($columns[$column_ct].'1', '服务平台1起期');
						$column_ct += 1;
						$objPHPExcel->setActiveSheetIndex(0)->setCellValue($columns[$column_ct].'1', '服务平台1止期');
						$column_ct += 1;
						$objPHPExcel->setActiveSheetIndex(0)->setCellValue($columns[$column_ct].'1', '服务平台2');
						$column_ct += 1;
						$objPHPExcel->setActiveSheetIndex(0)->setCellValue($columns[$column_ct].'1', '服务平台2起期');
						$column_ct += 1;
						$objPHPExcel->setActiveSheetIndex(0)->setCellValue($columns[$column_ct].'1', '服务平台2止期');
						$column_ct += 1;
						$objPHPExcel->setActiveSheetIndex(0)->setCellValue($columns[$column_ct].'1', '服务平台3');
						$column_ct += 1;
						$objPHPExcel->setActiveSheetIndex(0)->setCellValue($columns[$column_ct].'1', '服务平台3起期');
						$column_ct += 1;
						$objPHPExcel->setActiveSheetIndex(0)->setCellValue($columns[$column_ct].'1', '服务平台3止期');
						$column_ct += 1;
						$objPHPExcel->setActiveSheetIndex(0)->setCellValue($columns[$column_ct].'1', '服务平台4');
						$column_ct += 1;
						$objPHPExcel->setActiveSheetIndex(0)->setCellValue($columns[$column_ct].'1', '服务平台4起期');
						$column_ct += 1;
						$objPHPExcel->setActiveSheetIndex(0)->setCellValue($columns[$column_ct].'1', '服务平台4止期');
						$column_ct += 1;
						break;
					case 2:
						$objPHPExcel->setActiveSheetIndex(0)->setCellValue($columns[$column_ct].'1', '版本');
						$column_ct += 1;
						$objPHPExcel->setActiveSheetIndex(0)->setCellValue($columns[$column_ct].'1', '数量');
						$column_ct += 1;
						break;
						break;
					case 3:
						$objPHPExcel->setActiveSheetIndex(0)->setCellValue($columns[$column_ct].'1', '版本');
						$column_ct += 1;
						$objPHPExcel->setActiveSheetIndex(0)->setCellValue($columns[$column_ct].'1', '数量');
						$column_ct += 1;
						break;
				}
			}
			
			for($mt=1;$mt<13;$mt++)
			{
				$objPHPExcel->setActiveSheetIndex(0)->setCellValue($columns[$column_ct].'1', '2018年'.$mt.'月');$column_ct += 1;
			}

            $n = 2;
				
			$mod_statuses = new Db_Tables2_BDictContractStatus();
			$statuses = $mod_statuses->GetStatuses();
			
            foreach($result["client_name"] as $id => $something)
            {
				
				$column_ct = 0;
				
				$is_new_order = "";
				
//				if($result["dealer_id"][$id])
//				{
//					if($mod_contract->isRenew($result["contract_id"][$id]))
//					{
//						$is_new_order = "续签";
//					}else{
//						$is_new_order = "新签";
//					}	
//				}
				
				if(1 == $result["contract_type_id"][$id])
				{
					$contract_type = "付费合同";
				}else{
					$contract_type = "免费合同";
				}
				
                $objPHPExcel->setActiveSheetIndex(0)->setCellValue($columns[$column_ct].$n, isset($result["contract_sid"][$id])?$result["contract_sid"][$id]:"");$column_ct += 1;
                $objPHPExcel->setActiveSheetIndex(0)->setCellValue($columns[$column_ct].$n, isset($result["product_name"][$id])?$result["product_name"][$id]:"");$column_ct += 1;
                $objPHPExcel->setActiveSheetIndex(0)->setCellValue($columns[$column_ct].$n, isset($result["sign_date"][$id])?$result["sign_date"][$id]:"");$column_ct += 1;
                $objPHPExcel->setActiveSheetIndex(0)->setCellValue($columns[$column_ct].$n, isset($result["city_name"][$id])?$result["city_name"][$id]:"");$column_ct += 1;
                $objPHPExcel->setActiveSheetIndex(0)->setCellValue($columns[$column_ct].$n, isset($result["sales_emp_name"][$id])?$result["sales_emp_name"][$id]:"");$column_ct += 1;
                $objPHPExcel->setActiveSheetIndex(0)->setCellValue($columns[$column_ct].$n, isset($result["brands"][$id])?$result["brands"][$id]:"");$column_ct += 1;
                $objPHPExcel->setActiveSheetIndex(0)->setCellValue($columns[$column_ct].$n, isset($result["factories"][$id])?$result["factories"][$id]:"");$column_ct += 1;
                $objPHPExcel->setActiveSheetIndex(0)->setCellValue($columns[$column_ct].$n, isset($result["city_name"][$id])?$result["city_name"][$id]:"");$column_ct += 1;
                $objPHPExcel->setActiveSheetIndex(0)->setCellValue($columns[$column_ct].$n, $this->getPayTypeName(isset($result["pay_type"][$id])?$result["pay_type"][$id]:""));$column_ct += 1;
                $objPHPExcel->setActiveSheetIndex(0)->setCellValue($columns[$column_ct].$n, isset($result["client_name"][$id])?$result["client_name"][$id]:"");$column_ct += 1;
                $objPHPExcel->setActiveSheetIndex(0)->setCellValue($columns[$column_ct].$n, isset($result["signer_company_name"][$id])?$result["signer_company_name"][$id]:"");$column_ct += 1;
                $objPHPExcel->setActiveSheetIndex(0)->setCellValue($columns[$column_ct].$n, isset($result["dealer_id"][$id])?$result["dealer_id"][$id]:"");$column_ct += 1;
                $objPHPExcel->setActiveSheetIndex(0)->setCellValue($columns[$column_ct].$n, isset($is_new_order)?$is_new_order:"");$column_ct += 1;
                $objPHPExcel->setActiveSheetIndex(0)->setCellValue($columns[$column_ct].$n, isset($result["client_type"][$id])?$result["client_type"][$id]:"");$column_ct += 1;
                $objPHPExcel->setActiveSheetIndex(0)->setCellValue($columns[$column_ct].$n, isset($result["owner_name"][$id])?$result["owner_name"][$id]:"");$column_ct += 1;
                $objPHPExcel->setActiveSheetIndex(0)->setCellValue($columns[$column_ct].$n, isset($result["start_date"][$id])?$result["start_date"][$id]:"");$column_ct += 1;
                $objPHPExcel->setActiveSheetIndex(0)->setCellValue($columns[$column_ct].$n, isset($result["expired_date"][$id])?$result["expired_date"][$id]:"");$column_ct += 1;
                $objPHPExcel->setActiveSheetIndex(0)->setCellValue($columns[$column_ct].$n, isset($result["payment_time"][$id])?substr($result["payment_time"][$id],0,10):"");$column_ct += 1;
                $objPHPExcel->setActiveSheetIndex(0)->setCellValue($columns[$column_ct].$n, isset($result["receivable_value"][$id])?$result["receivable_value"][$id]:"");$column_ct += 1;
                $objPHPExcel->setActiveSheetIndex(0)->setCellValue($columns[$column_ct].$n, isset($result["received_value"][$id])?$result["received_value"][$id]:"");$column_ct += 1;
                $objPHPExcel->setActiveSheetIndex(0)->setCellValue($columns[$column_ct].$n, isset($statuses[$result["status"][$id]])?$statuses[$result["status"][$id]]:"");$column_ct += 1;
                $objPHPExcel->setActiveSheetIndex(0)->setCellValue($columns[$column_ct].$n, isset($result["tips"][$id])?$result["tips"][$id]:"");$column_ct += 1;
                $objPHPExcel->setActiveSheetIndex(0)->setCellValue($columns[$column_ct].$n, $contract_type);$column_ct += 1;

				if($params['product_id'])
				{
					switch($params['product_id'])
					{
						case 1:
							$objPHPExcel->setActiveSheetIndex(0)->setCellValue($columns[$column_ct].$n, isset($result["service_count"][$id])?$result["service_count"][$id]:"");$column_ct += 1;
							
							if(!empty($result["services"][$id]))
							{
								$k = 0;
								
								$service_ct = count($result["services"][$id]);
								
								foreach($result["services"][$id] as $service_info)
								{
									if(0 == $k)
									{
										$objPHPExcel->setActiveSheetIndex(0)->setCellValue($columns[$column_ct].$n, isset($service_info['service_name'])?$service_info['service_name']:"");$column_ct += 1;
										$objPHPExcel->setActiveSheetIndex(0)->setCellValue($columns[$column_ct].$n, isset($service_info['start_date'])?$service_info['start_date']:"");$column_ct += 1;
										$objPHPExcel->setActiveSheetIndex(0)->setCellValue($columns[$column_ct].$n, isset($service_info['expired_date'])?$service_info['expired_date']:"");$column_ct += 1;
									}elseif(1 == $k)
									{
										$objPHPExcel->setActiveSheetIndex(0)->setCellValue($columns[$column_ct].$n, isset($service_info['service_name'])?$service_info['service_name']:"");$column_ct += 1;
										$objPHPExcel->setActiveSheetIndex(0)->setCellValue($columns[$column_ct].$n, isset($service_info['start_date'])?$service_info['start_date']:"");$column_ct += 1;
										$objPHPExcel->setActiveSheetIndex(0)->setCellValue($columns[$column_ct].$n, isset($service_info['expired_date'])?$service_info['expired_date']:"");$column_ct += 1;
									}elseif(2 == $k)
									{
										$objPHPExcel->setActiveSheetIndex(0)->setCellValue($columns[$column_ct].$n, isset($service_info['service_name'])?$service_info['service_name']:"");$column_ct += 1;
										$objPHPExcel->setActiveSheetIndex(0)->setCellValue($columns[$column_ct].$n, isset($service_info['start_date'])?$service_info['start_date']:"");$column_ct += 1;
										$objPHPExcel->setActiveSheetIndex(0)->setCellValue($columns[$column_ct].$n, isset($service_info['expired_date'])?$service_info['expired_date']:"");$column_ct += 1;
									}elseif(3 == $k)
									{
										$objPHPExcel->setActiveSheetIndex(0)->setCellValue($columns[$column_ct].$n, isset($service_info['service_name'])?$service_info['service_name']:"");$column_ct += 1;
										$objPHPExcel->setActiveSheetIndex(0)->setCellValue($columns[$column_ct].$n, isset($service_info['start_date'])?$service_info['start_date']:"");$column_ct += 1;
										$objPHPExcel->setActiveSheetIndex(0)->setCellValue($columns[$column_ct].$n, isset($service_info['expired_date'])?$service_info['expired_date']:"");$column_ct += 1;
									}
									
									$k += 1;
								}
								
								$column_ct += (4 - $service_ct) * 3;
							}
							break;
						case 2:
							$objPHPExcel->setActiveSheetIndex(0)->setCellValue($columns[$column_ct].$n, isset($result["version"][$id])?$result["version"][$id]:"");$column_ct += 1;
							$objPHPExcel->setActiveSheetIndex(0)->setCellValue($columns[$column_ct].$n, isset($result["quantity"][$id])?$result["quantity"][$id]:"");$column_ct += 1;
							break;
						case 3:
							$objPHPExcel->setActiveSheetIndex(0)->setCellValue($columns[$column_ct].$n, isset($result["version"][$id])?$result["version"][$id]:"");$column_ct += 1;
							$objPHPExcel->setActiveSheetIndex(0)->setCellValue($columns[$column_ct].$n, isset($result["quantity"][$id])?$result["quantity"][$id]:"");$column_ct += 1;
							break;
					}
				}
				
				$payment_log = $mod_logs_contract->GetPaymentAmountByMonth($result["contract_id"][$id]);
				
				for($mt=1;$mt<13;$mt++)
				{
					if(isset($payment_log['2018年'.$mt.'月']))
					{
						$value = $payment_log['2018年'.$mt.'月'];
					}else{
						$value = 0;
					}
					
					$objPHPExcel->setActiveSheetIndex(0)->setCellValue($columns[$column_ct].$n, isset($value)?$value:"");$column_ct += 1;
				}
				
                $n += 1;
            }
        }
		
		$rd = mt_rand(1000, 9999);
		$folder = "upload/reports/";
        $file_name = "contract-export1-".date("YmdHis").$rd.".xlsx";
        $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
        $objWriter->save($folder.$file_name);
		
//        header("Location: /".$folder.$file_name);

        echo "<a href='/".$folder.$file_name."'>点击下载</a>";
        die;

    }

    public function getPayTypeName($payType){
        if($payType == 1){
            return "预付";
        }
        else if ($payType == 2){
            return "后付";
        }
        else{
            return "";
        }
    }


    public function indexExport2Action()
    {
        $params = $this->_request->getParams();
        $objPHPExcel = new PHPExcel();
		$mod_contract = new Db_Tables2_BContract();
		$mod_logs_contract = new Db_Tables2_BLogsContract();
		
		$dealers_db = Zend_Registry::get("dealers_db");
		$select = $dealers_db->select();
		$select->from("b_bu_auth", "*");
		$select->where("emp_id = ?", $_SESSION['identity']['userid']);
		$row = $dealers_db->fetchRow($select);
		
		$mod_reports = new Db_Joins_ReportsJoins();
		$mod_reports->skip_pagination = 1;
		$mod_reports->emp_auth_row = $row;
    	
		if($params['start_date_start'])
		{
			$mod_reports->start_date_start = $params['start_date_start'];
		}
    	
		if($params['start_date_end'])
		{
			$mod_reports->start_date_end = $params['start_date_end'];
		}
    	
		if($params['expired_date_start'])
		{
			$mod_reports->expired_date_start = $params['expired_date_start'];
		}
    	
		if($params['expired_date_end'])
		{
			$mod_reports->expired_date_end = $params['expired_date_end'];
		}
    	
		if($params['keyword'])
    	{
    		$mod_reports->keyword = $params['keyword'];
    	}
		
		if($params['group_id'])
    	{
    		$mod_reports->group_id = $params['group_id'];
    	}
		
		if($params['factory_id'])
    	{
    		$mod_reports->factory_id = $params['factory_id'];
    	}
		
		if($params['product_id'])
    	{
    		$mod_reports->product_id = $params['product_id'];
    	}
		
		if($params['provinceId'])
    	{
    		$mod_reports->province_id = $params['provinceId'];
    	}
		
		if($params['cityId'])
    	{
    		$mod_reports->city_id = $params['cityId'];
    	}
		
		if($params['sort_type'])
    	{
    		$mod_reports->sort_type = $params['sort_type'];
		}else{
			$mod_reports->sort_type = 1;
		}
		
		if(!$params['page_id'])
    	{
    		$page_id = 1;
    	}else{
    		$page_id = $params['page_id'];
    	}
    	
    	if($page_id)
    	{
    		$mod_reports->page_id = $page_id;
    		$this->view->page_id = $page_id;
    	}
		
		$result = $mod_reports->ContractExport2();
		
        $result = $result['current_page_info'];
//		$ext = new Sys_Extensions();
//		$ext->FormatArray($result);die;
        if(!empty($result))
        {
			$mod_ext = new Sys_Extensions();
			$columns = $mod_ext->ExcelColumnHeadGeneration(200);
			
			$column_ct = 0;
			
            //title
            $objPHPExcel->setActiveSheetIndex(0)->setCellValue($columns[$column_ct].'1', '合同号');
			$column_ct += 1;
            $objPHPExcel->setActiveSheetIndex(0)->setCellValue($columns[$column_ct].'1', '经销商渠道');
			$column_ct += 1;
            $objPHPExcel->setActiveSheetIndex(0)->setCellValue($columns[$column_ct].'1', '签单日期');
			$column_ct += 1;
            $objPHPExcel->setActiveSheetIndex(0)->setCellValue($columns[$column_ct].'1', '投放产品');
			$column_ct += 1;
            $objPHPExcel->setActiveSheetIndex(0)->setCellValue($columns[$column_ct].'1', '签约公司');
			$column_ct += 1;
            $objPHPExcel->setActiveSheetIndex(0)->setCellValue($columns[$column_ct].'1', '经销商ID');
			$column_ct += 1;
            $objPHPExcel->setActiveSheetIndex(0)->setCellValue($columns[$column_ct].'1', '经销商名称');
			$column_ct += 1;
            $objPHPExcel->setActiveSheetIndex(0)->setCellValue($columns[$column_ct].'1', 'ID性质');
			$column_ct += 1;
            $objPHPExcel->setActiveSheetIndex(0)->setCellValue($columns[$column_ct].'1', '客户名称');
			$column_ct += 1;
            $objPHPExcel->setActiveSheetIndex(0)->setCellValue($columns[$column_ct].'1', '经营品牌');
			$column_ct += 1;
            $objPHPExcel->setActiveSheetIndex(0)->setCellValue($columns[$column_ct].'1', '销售');
			$column_ct += 1;
            $objPHPExcel->setActiveSheetIndex(0)->setCellValue($columns[$column_ct].'1', '部门');
			$column_ct += 1;
            $objPHPExcel->setActiveSheetIndex(0)->setCellValue($columns[$column_ct].'1', '乙方单位');
			$column_ct += 1;
            $objPHPExcel->setActiveSheetIndex(0)->setCellValue($columns[$column_ct].'1', '签约类型');
			$column_ct += 1;
            $objPHPExcel->setActiveSheetIndex(0)->setCellValue($columns[$column_ct].'1', '金额');
			$column_ct += 1;
            $objPHPExcel->setActiveSheetIndex(0)->setCellValue($columns[$column_ct].'1', '服务起期');
			$column_ct += 1;
            $objPHPExcel->setActiveSheetIndex(0)->setCellValue($columns[$column_ct].'1', '服务止期');
			$column_ct += 1;
            $objPHPExcel->setActiveSheetIndex(0)->setCellValue($columns[$column_ct].'1', '执行天数');
			$column_ct += 1;
            $objPHPExcel->setActiveSheetIndex(0)->setCellValue($columns[$column_ct].'1', '省份');
			$column_ct += 1;
            $objPHPExcel->setActiveSheetIndex(0)->setCellValue($columns[$column_ct].'1', '城市');
			$column_ct += 1;
            $objPHPExcel->setActiveSheetIndex(0)->setCellValue($columns[$column_ct].'1', '合同类型');
            $column_ct += 1;
			
			if($params['product_id'])
			{
				switch($params['product_id'])
				{
					case 1:
						$objPHPExcel->setActiveSheetIndex(0)->setCellValue($columns[$column_ct].'1', '汽车之家');
						$column_ct += 1;
						$objPHPExcel->setActiveSheetIndex(0)->setCellValue($columns[$column_ct].'1', '易车');
						$column_ct += 1;
						$objPHPExcel->setActiveSheetIndex(0)->setCellValue($columns[$column_ct].'1', '爱卡');
						$column_ct += 1;
						$objPHPExcel->setActiveSheetIndex(0)->setCellValue($columns[$column_ct].'1', '太平洋');
						$column_ct += 1;
						$objPHPExcel->setActiveSheetIndex(0)->setCellValue($columns[$column_ct].'1', '行圆');
						$column_ct += 1;
						break;
					case 2:
						$objPHPExcel->setActiveSheetIndex(0)->setCellValue($columns[$column_ct].'1', '线索包');
						$column_ct += 1;
						$objPHPExcel->setActiveSheetIndex(0)->setCellValue($columns[$column_ct].'1', '会员版');
						$column_ct += 1;
						break;
					case 3:
						$objPHPExcel->setActiveSheetIndex(0)->setCellValue($columns[$column_ct].'1', '省心版');
						$column_ct += 1;
						$objPHPExcel->setActiveSheetIndex(0)->setCellValue($columns[$column_ct].'1', '清洗版');
						$column_ct += 1;
						$objPHPExcel->setActiveSheetIndex(0)->setCellValue($columns[$column_ct].'1', '唤醒版');
						$column_ct += 1;
						break;
				}
			}
			
			//获取起止时间
			$total_start_date = "2020-01-01";
			$total_expired_date = "2000-01-01";
			
			if(!empty($result["start_date"]))
			{
				foreach($result['start_date'] as $start_date)
				{
					if($total_start_date > $start_date)
					{
						$total_start_date = $start_date;
					}
				}
			}
			
			if(!empty($result["expired_date"]))
			{
				foreach($result['expired_date'] as $expired_date)
				{
					if($total_expired_date < $expired_date)
					{
						$total_expired_date = $expired_date;
					}
				}
			}
			
			if($total_start_date <= $total_expired_date)
			{
				$start_year = substr($total_start_date, 0, 4);
				$start_month = substr($total_start_date, 5, 2);
				$expired_year = substr($total_expired_date, 0, 4);
				$expired_month = substr($total_expired_date, 5, 2);
				
				while($start_year.$start_month <= $expired_year.$expired_month)
				{
					$objPHPExcel->setActiveSheetIndex(0)->setCellValue($columns[$column_ct].'1', $start_year."年".$start_month."月");$column_ct += 1;
					
					$nextmonth = date("Y-m", mktime(0,0,0,$start_month+1,1,$start_year));
					
					$start_year = substr($nextmonth, 0, 4);
					$start_month = substr($nextmonth, 5, 2);
				}
			}
			
			if($params['product_id'])
			{
				if(1 == $params['product_id'])
				{
					$objPHPExcel->setActiveSheetIndex(0)->setCellValue($columns[$column_ct].'1', '汽车之家开始');
					$column_ct += 1;
					$objPHPExcel->setActiveSheetIndex(0)->setCellValue($columns[$column_ct].'1', '汽车之家结束');
					$column_ct += 1;
					$objPHPExcel->setActiveSheetIndex(0)->setCellValue($columns[$column_ct].'1', '易车开始');
					$column_ct += 1;
					$objPHPExcel->setActiveSheetIndex(0)->setCellValue($columns[$column_ct].'1', '易车结束');
					$column_ct += 1;
					$objPHPExcel->setActiveSheetIndex(0)->setCellValue($columns[$column_ct].'1', '爱卡开始');
					$column_ct += 1;
					$objPHPExcel->setActiveSheetIndex(0)->setCellValue($columns[$column_ct].'1', '爱卡结束');
					$column_ct += 1;
					$objPHPExcel->setActiveSheetIndex(0)->setCellValue($columns[$column_ct].'1', '太平洋开始');
					$column_ct += 1;
					$objPHPExcel->setActiveSheetIndex(0)->setCellValue($columns[$column_ct].'1', '太平洋结束');
					$column_ct += 1;
					$objPHPExcel->setActiveSheetIndex(0)->setCellValue($columns[$column_ct].'1', '行圆开始');
					$column_ct += 1;
					$objPHPExcel->setActiveSheetIndex(0)->setCellValue($columns[$column_ct].'1', '行圆结束');
					$column_ct += 1;
				}
			}

            $n = 2;
			
            foreach($result["client_name"] as $id => $something)
            {
				$column_ct = 0;
				
				if(1 == $result["dealer_type"][$id])
				{
					$dealer_type = "4S";
				}elseif(2 == $result["dealer_type"][$id])
				{
					$dealer_type = "展厅";
				}elseif(3 == $result["dealer_type"][$id])
				{
					$dealer_type = "综合店";
				}else{
					$dealer_type = "";
				}
				
				if(1 == $result["contract_type_id"][$id])
				{
					$contract_type = "付费合同";
				}else{
					$contract_type = "免费合同";
				}
				
				$start_date_timestamp = mktime(0,0,0,substr($result["start_date"][$id],5,2),substr($result["start_date"][$id],8,2),substr($result["start_date"][$id],0,4));
				$expired_date_timestamp = mktime(0,0,0,substr($result["expired_date"][$id],5,2),substr($result["expired_date"][$id],8,2),substr($result["expired_date"][$id],0,4));
				
				$total_days = ceil(($expired_date_timestamp - $start_date_timestamp) / (3600 * 24)) + 1;
				
                $objPHPExcel->setActiveSheetIndex(0)->setCellValue($columns[$column_ct].$n, $result["contract_sid"][$id]);$column_ct += 1;
                $objPHPExcel->setActiveSheetIndex(0)->setCellValue($columns[$column_ct].$n, $result["channel_txt"][$id]);$column_ct += 1;
                $objPHPExcel->setActiveSheetIndex(0)->setCellValue($columns[$column_ct].$n, $result["sign_date"][$id]);$column_ct += 1;
                $objPHPExcel->setActiveSheetIndex(0)->setCellValue($columns[$column_ct].$n, $result["product_name"][$id]);$column_ct += 1;
                $objPHPExcel->setActiveSheetIndex(0)->setCellValue($columns[$column_ct].$n, $result["signer_company_name"][$id]);$column_ct += 1;
                $objPHPExcel->setActiveSheetIndex(0)->setCellValue($columns[$column_ct].$n, $result["dealer_id"][$id]);$column_ct += 1;
                $objPHPExcel->setActiveSheetIndex(0)->setCellValue($columns[$column_ct].$n, $result["dealer_name"][$id]);$column_ct += 1;
                $objPHPExcel->setActiveSheetIndex(0)->setCellValue($columns[$column_ct].$n, $dealer_type);$column_ct += 1;
                $objPHPExcel->setActiveSheetIndex(0)->setCellValue($columns[$column_ct].$n, $result["client_name"][$id]);$column_ct += 1;
                $objPHPExcel->setActiveSheetIndex(0)->setCellValue($columns[$column_ct].$n, $result["brand_txt"][$id]);$column_ct += 1;
                $objPHPExcel->setActiveSheetIndex(0)->setCellValue($columns[$column_ct].$n, $result["sales_emp_name"][$id]);$column_ct += 1;
                $objPHPExcel->setActiveSheetIndex(0)->setCellValue($columns[$column_ct].$n, "");$column_ct += 1;
                $objPHPExcel->setActiveSheetIndex(0)->setCellValue($columns[$column_ct].$n, $result["owner_name"][$id]);$column_ct += 1;
                $objPHPExcel->setActiveSheetIndex(0)->setCellValue($columns[$column_ct].$n, 2==$result["sign_type"][$id]?"集采":"单签");$column_ct += 1;
                $objPHPExcel->setActiveSheetIndex(0)->setCellValue($columns[$column_ct].$n, $result["actual_pay"][$id]);$column_ct += 1;
                $objPHPExcel->setActiveSheetIndex(0)->setCellValue($columns[$column_ct].$n, $result["start_date"][$id]);$column_ct += 1;
                $objPHPExcel->setActiveSheetIndex(0)->setCellValue($columns[$column_ct].$n, $result["expired_date"][$id]);$column_ct += 1;
                $objPHPExcel->setActiveSheetIndex(0)->setCellValue($columns[$column_ct].$n, $total_days);$column_ct += 1;
                $objPHPExcel->setActiveSheetIndex(0)->setCellValue($columns[$column_ct].$n, $result["province_name"][$id]);$column_ct += 1;
                $objPHPExcel->setActiveSheetIndex(0)->setCellValue($columns[$column_ct].$n, $result["city_name"][$id]);$column_ct += 1;
                $objPHPExcel->setActiveSheetIndex(0)->setCellValue($columns[$column_ct].$n, $contract_type);$column_ct += 1;
				
				if($params['product_id'])
				{
					switch($params['product_id'])
					{
						case 1:
							$column_1 = $column_2 = $column_3 = $column_4 = $column_5 = "";
							
							if(!empty($result["services"][$id]))
							{
								foreach($result["services"][$id] as $service_id => $service_info)
								{
									if('汽车之家' == $service_info['service_name'])
									{
										$column_1 = 1;
									}elseif('易车' == $service_info['service_name'])
									{
										$column_2 = 1;
									}elseif('爱卡' == $service_info['service_name'])
									{
										$column_3 = 1;
									}elseif('太平洋' == $service_info['service_name'])
									{
										$column_4 = 1;
									}elseif('行圆' == $service_info['service_name'])
									{
										$column_5 = 1;
									}
								}
							}
								
							$objPHPExcel->setActiveSheetIndex(0)->setCellValue($columns[$column_ct].$n, $column_1);$column_ct += 1;
							$objPHPExcel->setActiveSheetIndex(0)->setCellValue($columns[$column_ct].$n, $column_2);$column_ct += 1;
							$objPHPExcel->setActiveSheetIndex(0)->setCellValue($columns[$column_ct].$n, $column_3);$column_ct += 1;
							$objPHPExcel->setActiveSheetIndex(0)->setCellValue($columns[$column_ct].$n, $column_4);$column_ct += 1;
							$objPHPExcel->setActiveSheetIndex(0)->setCellValue($columns[$column_ct].$n, $column_5);$column_ct += 1;
							
							break;
						case 2:
							if('线索包' == $result["version"][$id])
							{
								$objPHPExcel->setActiveSheetIndex(0)->setCellValue($columns[$column_ct].$n, "1");$column_ct += 1;
							}else{
								$objPHPExcel->setActiveSheetIndex(0)->setCellValue($columns[$column_ct].$n, "");$column_ct += 1;
							}
							
							if('会员版' == $result["version"][$id])
							{
								$objPHPExcel->setActiveSheetIndex(0)->setCellValue($columns[$column_ct].$n, "1");$column_ct += 1;
							}else{
								$objPHPExcel->setActiveSheetIndex(0)->setCellValue($columns[$column_ct].$n, "");$column_ct += 1;
							}
							
							break;
						case 3:
							if('省心版' == $result["version"][$id])
							{
								$objPHPExcel->setActiveSheetIndex(0)->setCellValue($columns[$column_ct].$n, "1");$column_ct += 1;
							}else{
								$objPHPExcel->setActiveSheetIndex(0)->setCellValue($columns[$column_ct].$n, "");$column_ct += 1;
							}
							
							if('清洗版' == $result["version"][$id])
							{
								$objPHPExcel->setActiveSheetIndex(0)->setCellValue($columns[$column_ct].$n, "1");$column_ct += 1;
							}else{
								$objPHPExcel->setActiveSheetIndex(0)->setCellValue($columns[$column_ct].$n, "");$column_ct += 1;
							}
							
							if('唤醒版' == $result["version"][$id])
							{
								$objPHPExcel->setActiveSheetIndex(0)->setCellValue($columns[$column_ct].$n, "1");$column_ct += 1;
							}else{
								$objPHPExcel->setActiveSheetIndex(0)->setCellValue($columns[$column_ct].$n, "");$column_ct += 1;
							}
							
							break;
					}
				}
                
				if($total_start_date <= $total_expired_date)
				{
					$start_year = substr($total_start_date, 0, 4);
					$start_month = substr($total_start_date, 5, 2);
					$expired_year = substr($total_expired_date, 0, 4);
					$expired_month = substr($total_expired_date, 5, 2);

					while($start_year.$start_month <= $expired_year.$expired_month)
					{
						$current_start_date = $start_year."-".$start_month."-01";
						$current_expired_date = date("Y-m-d", mktime(0,0,0,$start_month+1,0,$start_year));
						
						if($current_expired_date < $result["start_date"][$id] || $current_start_date > $result["expired_date"][$id])
						{
							$actual_days = 0;
							$ignore = 1;
						}elseif($current_expired_date <= $result["expired_date"][$id] && $current_start_date <= $result["start_date"][$id]){
							$actual_start_date = $result["start_date"][$id];
							$actual_expired_date = $current_expired_date;
							$ignore = 0;
						}elseif($current_expired_date >= $result["expired_date"][$id] && $current_start_date >= $result["start_date"][$id]){
							$actual_start_date = $current_start_date;
							$actual_expired_date = $result["expired_date"][$id];
							$ignore = 0;
						}else{
							$actual_start_date = $current_start_date;
							$actual_expired_date = $current_expired_date;
							$ignore = 0;
						}
						
						if(!$ignore)
						{
							$actual_start_date_timestamp = mktime(0,0,0,substr($actual_start_date,5,2),substr($actual_start_date,8,2),substr($actual_start_date,0,4));
							$actual_expired_date_timestamp = mktime(0,0,0,substr($actual_expired_date,5,2),substr($actual_expired_date,8,2),substr($actual_expired_date,0,4));

							$actual_days = ceil(($actual_expired_date_timestamp - $actual_start_date_timestamp) / (3600 * 24));
						}
						
						$month_value = round($actual_days / $total_days * $result["actual_pay"][$id]);
						
						$objPHPExcel->setActiveSheetIndex(0)->setCellValue($columns[$column_ct].$n, $month_value);$column_ct += 1;

						$nextmonth = date("Y-m", mktime(0,0,0,$start_month+1,1,$start_year));

						$start_year = substr($nextmonth, 0, 4);
						$start_month = substr($nextmonth, 5, 2);
					}
				}
				
				if($params['product_id'])
				{
					switch($params['product_id'])
					{
						case 1:
							if(!empty($result["services"][$id]))
							{
								foreach($result["services"][$id] as $service_id => $service_info)
								{
									if('汽车之家' == $service_info['service_name'])
									{
										if($service_info['start_date'] != $result["start_date"][$id] || $service_info['expired_date'] != $result["expired_date"][$id])
										{
											$objPHPExcel->setActiveSheetIndex(0)->setCellValue($columns[$column_ct].$n, $service_info['start_date']);$column_ct += 1;
											$objPHPExcel->setActiveSheetIndex(0)->setCellValue($columns[$column_ct].$n, $service_info['expired_date']);$column_ct += 1;
										}else{
											$objPHPExcel->setActiveSheetIndex(0)->setCellValue($columns[$column_ct].$n, "");$column_ct += 1;
											$objPHPExcel->setActiveSheetIndex(0)->setCellValue($columns[$column_ct].$n, "");$column_ct += 1;
										}
									}
								}
								
								foreach($result["services"][$id] as $service_id => $service_info)
								{
									if('易车' == $service_info['service_name'])
									{
										if($service_info['start_date'] != $result["start_date"][$id] || $service_info['expired_date'] != $result["expired_date"][$id])
										{
											$objPHPExcel->setActiveSheetIndex(0)->setCellValue($columns[$column_ct].$n, $service_info['start_date']);$column_ct += 1;
											$objPHPExcel->setActiveSheetIndex(0)->setCellValue($columns[$column_ct].$n, $service_info['expired_date']);$column_ct += 1;
										}else{
											$objPHPExcel->setActiveSheetIndex(0)->setCellValue($columns[$column_ct].$n, "");$column_ct += 1;
											$objPHPExcel->setActiveSheetIndex(0)->setCellValue($columns[$column_ct].$n, "");$column_ct += 1;
										}
									}
								}
								
								foreach($result["services"][$id] as $service_id => $service_info)
								{
									if('爱卡' == $service_info['service_name'])
									{
										if($service_info['start_date'] != $result["start_date"][$id] || $service_info['expired_date'] != $result["expired_date"][$id])
										{
											$objPHPExcel->setActiveSheetIndex(0)->setCellValue($columns[$column_ct].$n, $service_info['start_date']);$column_ct += 1;
											$objPHPExcel->setActiveSheetIndex(0)->setCellValue($columns[$column_ct].$n, $service_info['expired_date']);$column_ct += 1;
										}else{
											$objPHPExcel->setActiveSheetIndex(0)->setCellValue($columns[$column_ct].$n, "");$column_ct += 1;
											$objPHPExcel->setActiveSheetIndex(0)->setCellValue($columns[$column_ct].$n, "");$column_ct += 1;
										}
									}
								}
								
								foreach($result["services"][$id] as $service_id => $service_info)
								{
									if('太平洋' == $service_info['service_name'])
									{
										if($service_info['start_date'] != $result["start_date"][$id] || $service_info['expired_date'] != $result["expired_date"][$id])
										{
											$objPHPExcel->setActiveSheetIndex(0)->setCellValue($columns[$column_ct].$n, $service_info['start_date']);$column_ct += 1;
											$objPHPExcel->setActiveSheetIndex(0)->setCellValue($columns[$column_ct].$n, $service_info['expired_date']);$column_ct += 1;
										}else{
											$objPHPExcel->setActiveSheetIndex(0)->setCellValue($columns[$column_ct].$n, "");$column_ct += 1;
											$objPHPExcel->setActiveSheetIndex(0)->setCellValue($columns[$column_ct].$n, "");$column_ct += 1;
										}
									}
								}
								
								foreach($result["services"][$id] as $service_id => $service_info)
								{
									if('行圆' == $service_info['service_name'])
									{
										if($service_info['start_date'] != $result["start_date"][$id] || $service_info['expired_date'] != $result["expired_date"][$id])
										{
											$objPHPExcel->setActiveSheetIndex(0)->setCellValue($columns[$column_ct].$n, $service_info['start_date']);$column_ct += 1;
											$objPHPExcel->setActiveSheetIndex(0)->setCellValue($columns[$column_ct].$n, $service_info['expired_date']);$column_ct += 1;
										}else{
											$objPHPExcel->setActiveSheetIndex(0)->setCellValue($columns[$column_ct].$n, "");$column_ct += 1;
											$objPHPExcel->setActiveSheetIndex(0)->setCellValue($columns[$column_ct].$n, "");$column_ct += 1;
										}
									}
								}
							}
							
							break;
					}
				}
				
                $n += 1;
            }
        }
		
		$rd = mt_rand(1000, 9999);
		$folder = "upload/reports/";
        $file_name = "contract-export2-".date("YmdHis").$rd.".xlsx";
        $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
        $objWriter->save($folder.$file_name);
        header("Location: /".$folder.$file_name);

        echo "End.";
        die;

    }
	
	function addContractAction()
	{
		$params = $this->_request->getParams();
		
		if(2 == $params['type'])
		{
			$this->view->title = "申请免费合同 第一步：选择客户";
		}else{
			$this->view->title = "申请付费合同 第一步：选择客户";
		}
		
		$this->view->contract_type_id = $params['type'];
	}
	
	function addContractStep2Action()
	{
		$params = $this->_request->getParams();
//		$ext = new Sys_Extensions();
//		$ext->FormatArray($_SESSION['contract']);die;
		if($params['client_id']) //新建合同
		{
			$this->view->title = "申请合同 第二步：完成合同";
			
			if(2 == $params['contract_type_id'])
			{
				$this->view->title = "申请免费合同 第二步：完成合同";
				$contract_type_id = 2;
			}else{
				$this->view->title = "申请付费合同 第二步：完成合同";
				$contract_type_id = 1; //默认付费合同
			}

			$mod_client = new Db_Tables2_BClient();
			$detail = $mod_client->FetchClientDetail($params['client_id'], 1);

			if(!empty($detail))
			{
				$_SESSION['contract'] = array(
					"client_info" => array(),
					"contract_info" => array(
						"contract_sid" => NULL,
						"contract_type_id" => $contract_type_id,
						"start_date" => NULL,
						"expired_date" => NULL,
						"signer_id" => NULL,
						"signer_company_name" => NULL,
						"owner_id" => NULL,
						"owner_name" => NULL,
						"contract_claim_amount" => 0,
						"contract_value" => 0,
						"contract_cost" => 0,
						"tips" => NULL,
						"dealers_arr" => array(),
						"dealers_str" => "",
						"pay_type" => NULL,
						"sign_type" => NULL,
						"invoice_type" => NULL
					),
					"sku_info" => array()
				);
				
				if($params['parent_contract_id'])
				{
					$_SESSION['contract']['contract_info']['parent_contract_id'] = $params['parent_contract_id'];
				}
				
				if($params['parent_contract_sid'])
				{
					$_SESSION['contract']['contract_info']['parent_contract_sid'] = $params['parent_contract_sid'];
				}
				
				if($params['signer_id'])
				{
					$_SESSION['contract']['contract_info']['signer_id'] = $params['signer_id'];
				}
				
				if($params['owner_id'])
				{
					$_SESSION['contract']['contract_info']['owner_id'] = $params['owner_id'];
				}
				
				if($params['pay_type'])
				{
					$_SESSION['contract']['contract_info']['pay_type'] = $params['pay_type'];
				}
				
				if($params['sign_type'])
				{
					$_SESSION['contract']['contract_info']['sign_type'] = $params['sign_type'];
				}
				
				$_SESSION['contract']['client_info'] = $detail;
				
				if($detail['is_dealer'])
				{
					$mod_dealer = new Db_Tables2_TDealer();
					$dealer = $mod_dealer->FetchDealerDetail($detail['is_dealer']);
					
					if($dealer)
					{
						$_SESSION['contract']['contract_info']['dealers_arr'][$dealer['id']] = $dealer['companyName'];
						$_SESSION['contract']['contract_info']['dealers_str'] = $detail['is_dealer'];
					}
				}
				
				$mod_signer = new Db_Tables2_BClientSigner();
				$this->view->signers = $mod_signer->GetClientSigner($params['client_id']);
				
				$mod_owner = new Db_Tables2_BOwner();
				$this->view->owners = $mod_owner->GetOwners();
				
				$mod_params = new Db_Tables2_BDictParams();
				$sales_role_id = array();
				$sales_role_id[] = $mod_params->GetVal("LEVEL-1");
				$sales_role_id[] = $mod_params->GetVal("LEVEL-2");
				
				$mod_user = new Db_Tables2_User();
				$this->view->sales = $mod_user->GetUsersByRole($sales_role_id);
			}else{
				$this->_redirect("/contracts/add-contract");
			}
		}elseif($_SESSION['contract']){
			if(2 == $_SESSION['contract']['contract_info']['contract_type_id'])
			{
				$this->view->title = "申请免费合同 第二步：完成合同";
			}else{
				$this->view->title = "申请付费合同 第二步：完成合同";
			}
			
			$mod_signer = new Db_Tables2_BClientSigner();
			$this->view->signers = $mod_signer->GetClientSigner($_SESSION['contract']['client_info']['client_id']);
			
			$mod_owner = new Db_Tables2_BOwner();
			$this->view->owners = $mod_owner->GetOwners();
				
			$mod_params = new Db_Tables2_BDictParams();
			$sales_role_id = array();
			$sales_role_id[] = $mod_params->GetVal("LEVEL-1");
			$sales_role_id[] = $mod_params->GetVal("LEVEL-2");
			
			$mod_user = new Db_Tables2_User();
			$this->view->sales = $mod_user->GetUsersByRole($sales_role_id);
		}else{
			$this->_redirect("/contracts");
		}
		
		$mod_invoice_name = new Db_Tables2_BDictProductInvoiceName();
		$this->view->invoice_names = $mod_invoice_name->MakeArr();
		
		$mod_invoice_version = new Db_Tables2_BDictProductInvoiceVersion();
		$this->view->invoice_versions = $mod_invoice_version->MakeArr();
		
		if($params['msg'])
		{
				switch ($params['msg'])
				{
					case 1:
						$this->view->msg = "新增产品成功";
						break;
					case 2:
						$this->view->msg = "新增产品失败";
						break;
					case 3:
						$this->view->msg = "新增回款计划成功";
						break;
				}
		}
	}
	
	function addSkuIntoContractAction()
	{
		$params = $this->_request->getParams();
		$this->view->title = "申请合同 添加产品";
				
		$mod_product = new Db_Tables2_BDictProduct();
		$this->view->products = $mod_product->GetProducts();
				
		$mod_service = new Db_Tables2_BDictService();
		$this->view->services = $mod_service->GetServices();
		
		if($params['contract_id'])
		{
			$this->view->contract_id = $params['contract_id'];
		}
		
		$mod_ext = new Sys_Extensions();
		
		if($params['contract_id'])
		{
			$existed_product_ids = $mod_ext->GetProductIds($_SESSION['contract-edit-type2'][$params['contract_id']]['sku_info']);
		}else{
			$existed_product_ids = $mod_ext->GetProductIds($_SESSION['contract']['sku_info']);
		}
		
		$this->view->existed_product_ids = $existed_product_ids;
	}
	
	function addSkuIntoContractSubmitAction()
	{
		$params = $this->_request->getParams();
//		$ext = new Sys_Extensions();
//		$ext->FormatArray($params);die;	
		
		if($params['sku_id'] && $params['new_sku_quantity'])
		{
			$row = array(
				"sku_id" => $params['sku_id'],
				"sku_quantity" => $params['new_sku_quantity'],
				"actual_pay" => $params['new_actual_pay'],
				"start_date" => $params['start_date'],
				"expired_date" => $params['expired_date'],
				"service_ids" => $params['service_ids'],
                'hxb_account' => $params['hxb_account'],
                "dealer_id" => $params['dealer_id'],
                "product_id"=>$params['product_id'],
                "961_bonus"=>$params['new_bonus']
			);
			
			if(!empty($params['service_ids']))
			{
				foreach($params['service_ids'] as $service_id)
				{
					$row['start_date_'.$service_id] = $params['start_date_'.$service_id];
					$row['expired_date_'.$service_id] = $params['expired_date_'.$service_id];
				}
			}
			
			if($params['contract_id'])
			{
				$_SESSION['contract-edit-type2'][$params['contract_id']]['sku_info'][] = $row;
				
				$mod_ext = new Sys_Extensions();
				$mod_ext->ReCalculateNewContract($params['contract_id']);
				
				$this->_redirect("/contracts/edit-contract-type2/contract_id/".$params['contract_id']."/msg/1");
			}else{
				$_SESSION['contract']['sku_info'][] = $row;

				$mod_ext = new Sys_Extensions();
				$mod_ext->ReCalculateNewContract();

				$this->_redirect("/contracts/add-contract-step2/msg/1");
			}
		}else{
			echo "关键参数缺失";
			die;
		}
	}
	
	function addDealersIntoContractAction()
	{
		$params = $this->_request->getParams();
		$this->view->title = "申请合同 经销商明细";
		
		if($params['contract_id'])
		{
			$this->view->contract_id = $params['contract_id'];
		}
	}
	
	function addDealersIntoContractSubmitAction()
	{
		$params = $this->_request->getParams();
		
		if($params['contract_id'])
		{
			$target_session = $_SESSION['contract-edit-type2'][$params['contract_id']];	
		}else{
			$target_session = $_SESSION['contract'];
		}
		
		if($params['dealer_id'] && $target_session)
		{
			if(!$target_session['contract_info']['dealers_arr'][$params['dealer_id']])
			{
				$mod_dealer = new Db_Tables2_TDealer();
				$dealer_info = $mod_dealer->FetchDealerDetail($params['dealer_id']);

				if($dealer_info)
				{
					$target_session['contract_info']['dealers_arr'][$params['dealer_id']] = $dealer_info['companyName'];
				}
			}
			
			if($params['contract_id'])
			{
				$_SESSION['contract-edit-type2'][$params['contract_id']] = $target_session;	
				
				$ext = new Sys_Extensions();
				$ext->MakeDealerStringInContract($params['contract_id']);
				
				$this->_redirect("/contracts/add-dealers-into-contract/contract_id/".$params['contract_id']);
			}else{
				$_SESSION['contract'] = $target_session;
				
				$ext = new Sys_Extensions();
				$ext->MakeDealerStringInContract();
			}
		}
		
		$this->_redirect("/contracts/add-dealers-into-contract");
	}
	
	function addPayPlanAction()
	{
		$params = $this->_request->getParams();
		$this->view->title = "申请合同 添加回款计划";
		
		if($params['contract_id'])
		{
			$this->view->contract_id = $params['contract_id'];
		}
	}
	
	function addPayPlanSubmitAction()
	{
		$params = $this->_request->getParams();
		
		if($params['plan_date'] && $params['plan_value'])
		{
			$row = array(
				"plan_date" => $params['plan_date'],
				"plan_value" => $params['plan_value'],
				"tips" => $params['tips']
			);
			
			if($params['contract_id'])
			{
				$_SESSION['contract-edit-type2'][$params['contract_id']]['pay_plan'][] = $row;
				
				$this->_redirect("/contracts/edit-contract-type2/contract_id/".$params['contract_id']."/msg/3#pay-plan");
			}else{
				$_SESSION['contract']['pay_plan'][] = $row;

				$this->_redirect("/contracts/add-contract-step2/msg/3#pay-plan");
			}
		}else{
			echo "关键参数缺失";
			die;
		}
	}
	
	function addPayPlan2Action()
	{
		$params = $this->_request->getParams();
		$this->view->title = "添加回款计划";
		
		if($params['contract_id'])
		{
			$dealers_db = Zend_Registry::get('dealers_db');
			$select = $dealers_db->select();
			$select->from("b_contract as c", array("sales_emp_id"));
			$select->where("c.contract_id = ?", $params['contract_id']);
			$contract_info = $dealers_db->fetchRow($select);
			
			if($contract_info['sales_emp_id'] == $_SESSION['identity']['userid'])
			{
				$this->view->contract_info = $contract_info;
				$this->view->contract_id = $params['contract_id'];
			}else{
				$this->_redirect("/contracts/view-contract/contract_id/".$params['contract_id']."/msg/4");
			}
		}else{
			$this->_redirect("/contracts/view-contract/contract_id/".$params['contract_id']."/msg/4");
		}
	}
	
	function addPayPlan2SubmitAction()
	{
		$params = $this->_request->getParams();
		
		if($params['plan_date'] && $params['plan_value'] && $params['contract_id'])
		{
			$row = array(
				"plan_date" => $params['plan_date'],
				"plan_value" => $params['plan_value'],
				"tips" => $params['tips']
			);
			
			$_SESSION['edit-pay-plans'][$params['contract_id']][] = $row;
			
			$this->_redirect("/contracts/edit-pay-plans/contract_id/".$params['contract_id']);
		}else{
			echo "关键参数缺失";
			die;
		}
	}
	
	function delDealerFromContractAction()
	{
		$params = $this->_request->getParams();
		
		if($params['dealer_id'])
		{
			if($params['contract_id'])
			{
				unset($_SESSION['contract-edit-type2'][$params['contract_id']]['contract_info']['dealers_arr'][$params['dealer_id']]);

				$ext = new Sys_Extensions();
				$ext->MakeDealerStringInContract($params['contract_id']);
				
				$this->_redirect("/contracts/add-dealers-into-contract/contract_id/".$params['contract_id']);
			}else{
				unset($_SESSION['contract']['contract_info']['dealers_arr'][$params['dealer_id']]);

				$ext = new Sys_Extensions();
				$ext->MakeDealerStringInContract();
			}
		}
		
		$this->_redirect("/contracts/add-dealers-into-contract");
	}
	
	function delSkuFromContractAction()
	{
		$params = $this->_request->getParams();
		
		if($params['contract_id'])
		{
			$target_session = $_SESSION['contract-edit-type2'][$params['contract_id']];	
		}else{
			$target_session = $_SESSION['contract'];
		}
		
		if(is_numeric($params['id']))
		{
			if($params['contract_id'])
			{
				unset($_SESSION['contract-edit-type2'][$params['contract_id']]['sku_info'][$params['id']]);

				$ext = new Sys_Extensions();
				$ext->ReCalculateNewContract($params['contract_id']);
				
				$this->_redirect("/contracts/edit-contract-type2/contract_id/".$params['contract_id']);
			}else{
				unset($_SESSION['contract']['sku_info'][$params['id']]);

				$ext = new Sys_Extensions();
				$ext->ReCalculateNewContract();
				
				$this->_redirect("/contracts/add-contract-step2");
			}
		}else{
			echo "参数缺失";
			die;
		}
	}
	
	function delPayPlanFromContractAction()
	{
		$params = $this->_request->getParams();
		
		if($params['contract_id'])
		{
			$target_session = $_SESSION['contract-edit-type2'][$params['contract_id']];	
		}else{
			$target_session = $_SESSION['contract'];
		}
		
		if(is_numeric($params['id']))
		{
			if($params['contract_id'])
			{
				unset($_SESSION['contract-edit-type2'][$params['contract_id']]['pay_plan'][$params['id']]);
				
				$this->_redirect("/contracts/edit-contract-type2/contract_id/".$params['contract_id']."#pay-plan");
			}else{
				unset($_SESSION['contract']['pay_plan'][$params['id']]);
				
				$this->_redirect("/contracts/add-contract-step2#pay-plan");
			}
		}else{
			echo "参数缺失";
			die;
		}
	}
	
	function delPayPlanFromContract2Action()
	{
		$params = $this->_request->getParams();
		
		if(is_numeric($params['id']))
		{
			if($params['contract_id'])
			{
				unset($_SESSION['edit-pay-plans'][$params['contract_id']][$params['id']]);
				
				$this->_redirect("/contracts/edit-pay-plans/contract_id/".$params['contract_id']);
			}
		}else{
			echo "参数缺失";
			die;
		}
	}
	
	function addContractSubmitAction()
	{
		$params = $this->_request->getParams();
//		$ext = new Sys_Extensions();
//		$ext->FormatArray($_SESSION['contract']);die;
		if($_SESSION['contract'])
		{
			$data = array(
				"contract_type_id" => $_SESSION['contract']['contract_info']['contract_type_id'],
				"province_id" => $_SESSION['contract']['client_info']['province_id'],
				"province_name" => $_SESSION['contract']['client_info']['province_name'],
				"city_id" => $_SESSION['contract']['client_info']['city_id'],
				"city_name" => $_SESSION['contract']['client_info']['city_name'],
				"start_date" => $_SESSION['contract']['contract_info']['start_date'],
				"expired_date" => $_SESSION['contract']['contract_info']['expired_date'],
				"sales_emp_id" => $_SESSION['identity']['userid'],
				"sales_emp_name" => $_SESSION['identity']['realname'],
				"client_id" => $_SESSION['contract']['client_info']['client_id'],
				"client_name" => $_SESSION['contract']['client_info']['client_name'],
				"client_type_id" => $_SESSION['contract']['client_info']['client_type_id'],
				"contract_claim_amount" => $_SESSION['contract']['contract_info']['contract_claim_amount'],
				"contract_value" => $_SESSION['contract']['contract_info']['contract_value'],
				"receivable_value" => $_SESSION['contract']['contract_info']['contract_value']-$_SESSION['contract']['contract_info']['contract_cost'],
				"status" => 0,
				"emp_id_1" => $_SESSION['identity']['userid'],
				"ctime" => date("Y-m-d H:i:s")
			);
			
			if($_SESSION['contract']['contract_info']['parent_contract_id'])
			{
				$data['parent_contract_id'] = $_SESSION['contract']['contract_info']['parent_contract_id'];
			}
			
			if($_SESSION['contract']['contract_info']['parent_contract_sid'])
			{
				$data['parent_contract_sid'] = $_SESSION['contract']['contract_info']['parent_contract_sid'];
			}
			
			//检查主表单是否改变
			
			//签约公司
			if(is_numeric($params['signer_id']))
			{
				if($params['signer_id'] != $_SESSION['contract']['contract_info']['signer_id'])
				{
					$mod_signer = new Db_Tables2_BSigner();
					$signer = $mod_signer->FetchSignerDetails($params['signer_id']);
					$signer_id = $params['signer_id'];
					$signer_company_name = $signer['company_name'];
				}else{
					$signer_id = $_SESSION['contract']['contract_info']['signer_id'];
					$signer_company_name = $_SESSION['contract']['contract_info']['signer_company_name'];
				}
			}else{
				$signer_id = NULL;
				$signer_company_name = NULL;
			}
			
			$data['signer_id'] = $signer_id;
			$data['signer_company_name'] = $signer_company_name;
			
			//乙方单位
			if(is_numeric($params['owner_id']))
			{
				if($params['owner_id'] != $_SESSION['contract']['contract_info']['owner_id'])
				{
					$mod_owner = new Db_Tables2_BOwner();
					$owner = $mod_owner->FetchOwnerDetails($params['owner_id']);
					$owner_id = $params['owner_id'];
					$owner_name = $owner['owner_name'];
				}else{
					$owner_id = $_SESSION['contract']['contract_info']['owner_id'];
					$owner_name = $_SESSION['contract']['contract_info']['owner_name'];
				}
			}else{
				$owner_id = NULL;
				$owner_name = NULL;
			}
			
			if($owner_id)
			{
				$data['owner_id'] = $owner_id;
				$data['owner_name'] = $owner_name;
			}
			
			//付款方式
			if(isset($params['pay_type']))
			{
				$data['pay_type'] = $params['pay_type'];
				
				if(2 == $params['pay_type'])
				{
					$data['pay_date'] = $params['pay_date'];
				}else{
					$data['pay_date'] = NULL;
				}
			}else{
				$data['pay_type'] = 4; //免费
			}
			
			//签约类型
			$data['sign_type'] = $params['sign_type'];
			
			if(2 == $params['sign_type'])
			{
				$data['key_account_sales'] = $params['key_account_sales'];
			}else{
				$data['key_account_sales'] = NULL;
			}
			
			//申请票种
			if($params['invoice_type'])
			{
				$data['invoice_type'] = $params['invoice_type'];
			}
			
			//备注
			if($params['tips'])
			{
				$data['tips'] = $params['tips'];
			}else{
				$data['tips'] = NULL;
			}
			
			$mod_user = new Db_Tables2_User();
			$my_leader = $mod_user->GetMyLeaders($_SESSION['identity']['userid']);
			
			//approved automatically
			/**
			 * 1 合同金额是刊例价的50%
			 * 2 预付
			 * 3 付费合同
			 */
			
			//取消预付且折扣50%不过销售主管审批的设置 2020.5.13
			
//			if($_SESSION['contract']['contract_info']['contract_claim_amount'] == $_SESSION['contract']['contract_info']['contract_value'] && 1==$data['pay_type'] && 1==$data['contract_type_id'])
//			{
//				$data['status'] = 1; //还需要合同管理员审 2018.3.5
//			}else
				
			if(empty($my_leader))
			{
				$data['status'] = 1; //最高级主管直接由合同管理员审
			}
			
			$dealers_db = Zend_Registry::get('dealers_db');
			$contract_id = 0;
			$contract_status = $data['status'];
			
			if($dealers_db->insert("b_contract", $data))
			{
				$select = $dealers_db->select();
				$select->from("b_contract", "contract_id");
				$select->order("contract_id DESC");
				$row = $dealers_db->fetchRow($select);
				
				if($row)
				{
					$contract_id = $row['contract_id'];
				}
			}
			
			if($contract_id)
			{
				//add approval log
				if(!$contract_status)
				{
					$approve_type = 0; //逐级审批
					
					if(!empty($_SESSION['contract']['sku_info']))
					{
						foreach($_SESSION['contract']['sku_info'] as $sku_info)
						{
							if(1138 == $sku_info['sku_id'])
							{
								$approve_type = 1; //爱双需求，网媒试用刊例只要最近一级主管审批 2019.07.20
								break;
							}
						}
					}
					
					//车智推先由孟居洲审
					//百度有驾也一样 2020.5.13
					$czt_product_id = 2;
					$bdyj_product_id = 14;
					
					$is_czt_contract = 0;
					
					$mod_skus = new Db_Tables2_BSku();
					
					if(!empty($_SESSION['contract']['sku_info']))
					{
						foreach($_SESSION['contract']['sku_info'] as $sku_info)
						{
							$si = $mod_skus->GetSkuRow($sku_info['sku_id']);
							
							if($si['product_id'] == $czt_product_id || $si['product_id'] == $bdyj_product_id)
							{
								$is_czt_contract = 1;
								break;
							}
						}
					}
					
					
					if($is_czt_contract)
					{
						$set = array(
							"type" => 2,
							"target_id" => $contract_id,
							"emp_id" => 626,
							"emp_name" => '孟居洲',
							"status" => 0
						);

						$dealers_db->insert("b_logs_sales_approval", $set);
					}
					
					//添加主管审批记录
					$leaders_arr = $mod_user->GetMyLeaders($_SESSION['identity']['userid'], $approve_type);
					
					if(!empty($leaders_arr))
					{
						foreach($leaders_arr as $leader)
						{
							$set = array(
								"type" => 2,
								"target_id" => $contract_id,
								"emp_id" => $leader['emp_id'],
								"emp_name" => $leader['emp_name'],
								"status" => 0
							);
							
							$dealers_db->insert("b_logs_sales_approval", $set);
						}
					}
				}
				
				//insert other info
				if(!empty($_SESSION['contract']['contract_info']['dealers_arr']))
				{
					foreach($_SESSION['contract']['contract_info']['dealers_arr'] as $dealer_id => $dealer_name)
					{
						$data = array(
							"contract_id" => $contract_id,
							"dealer_id" => $dealer_id,
							"dealer_name" => $dealer_name
						);
						
						$dealers_db->insert("b_contract_dealer", $data);
					}
				}
				
				if(!empty($_SESSION['contract']['sku_info']))
				{
					$mod_sku = new Db_Tables2_BSku();
					
					$lp = 0;
					
					foreach($_SESSION['contract']['sku_info'] as $skid => $sku_info)
					{
						$mail_token = sha1($contract_id.$lp);
						$lp += 1;
						
						$product_sku = $mod_sku->GetSkuRow($sku_info['sku_id']);
						
						$data = array(
							"contract_id" => $contract_id,
							"product_id" => $product_sku['product_id'],
							"product_name" => $product_sku['product_name'],
							"sku_id" => $sku_info['sku_id'],
							"sku_name" => $product_sku['sku_name'],
							"unit_name" => $product_sku['unit_name'],
							"unit_price" => $sku_info['unit_price'],
							"quantity" => $sku_info['sku_quantity'],
							"rrp" => $sku_info['unit_price'] * $sku_info['sku_quantity'],
							"claim_amount" => $sku_info['unit_price'] * $sku_info['sku_quantity'] / 2,
							"actual_pay" => $sku_info['actual_pay'],
							"start_date" => $sku_info['start_date'],
							"expired_date" => $sku_info['expired_date'],
							"mail_token" => $mail_token,
							"dealer_id" => $sku_info['dealer_id'],
                            "hxb_account" => $sku_info['hxb_account'],
                            "961_discount" => $sku_info['961_bonus']
                        );
						
						if(isset($params['sku_invoice_name_'.$skid]))
						{
							if($params['sku_invoice_name_'.$skid])
							{
								$data['invoice_name_id'] = $params['sku_invoice_name_'.$skid];
							}
						}
						
						if(isset($params['sku_invoice_version_'.$skid]))
						{
							if($params['sku_invoice_version_'.$skid])
							{
								$data['invoice_version_id'] = $params['sku_invoice_version_'.$skid];
							}
						}
						
						if($dealers_db->insert("b_contract_sku", $data))
						{
							if(!empty($sku_info['service_ids']))
							{
								$select = $dealers_db->select();
								$select->from("b_contract_sku", "cs_id");
								$select->order("contract_id DESC");
								$row = $dealers_db->fetchRow($select);

								if($row)
								{
									$cs_id = $row['cs_id'];
								}

								if($cs_id)
								{
									$mod_service = new Db_Tables2_BDictService();
									$services = $mod_service->GetServices();
									
									foreach($sku_info['service_ids'] as $service_id)
									{
										$data = array(
											"contract_id" => $contract_id,
											"cs_id" => $cs_id,
											"service_id" => $service_id,
											"service_name" => $services[$service_id],
											"start_date" => $sku_info['start_date_'.$service_id],
											"expired_date" => $sku_info['expired_date_'.$service_id]
										);

										$dealers_db->insert("b_contract_sku_service", $data);
									}
								}
							}
						}
					}
				}
				
				if($_SESSION['contract']['pay_plan'])
				{
					$ctime = date("Y-m-d H:i:s");
					
					foreach($_SESSION['contract']['pay_plan'] as $val)
					{
						$data = array(
							"contract_id" => $contract_id,
							"plan_date" => $val['plan_date'],
							"plan_value" => $val['plan_value'],
							"tips" => $val['tips'],
							"status" => 0,
							"ctime" => $ctime
						);
						
						$dealers_db->insert("b_logs_contract_pay_plan", $data);
					}
				}
				
				unset($_SESSION['contract']);
				
				$this->_redirect("/contracts/index/msg/1");
			}else{
				$this->_redirect("/contracts/add-contract/error/2"); //关键参数缺失
			}
		}else{
			$this->_redirect("/contracts/add-contract/error/1"); //关键参数缺失
		}
	}
	
	function editContractAction()
	{
		$params = $this->_request->getParams();
		$this->view->title = "编辑合同";
		
		if($params['contract_id'])
		{
			$dealers_db = Zend_Registry::get('dealers_db');
			
			$select = $dealers_db->select();
			$select->from("b_contract as c", array(
				"contract_id",
				"contract_sid",
				"province_id",
				"province_name",
				"city_id",
				"city_name",
				"start_date",
				"expired_date",
				"sign_date",
				"sales_emp_id",
				"sales_emp_name",
				"client_id",
				"client_name",
				"signer_id",
				"signer_company_name",
				"owner_id",
				"owner_name",
				"contract_claim_amount",
				"contract_value",
				"contract_cost",
				"receivable_value",
				"received_value",
				"tips",
				"status",
				"delivery_status",
				"launch_switcher",
				"ctime",
				"pay_type",
				"pay_date",
				"allow_edit"
			));
			$select->joinLeft("b_client_type as t", "t.client_type_id=c.client_type_id", array("name as client_type_name"));
			$select->where("c.contract_id = ?", $params['contract_id']);
			$contract_info = $dealers_db->fetchRow($select);
			
			$mod_client = new Db_Tables2_BClient();
			$client_info = $mod_client->FetchClientDetail($contract_info['client_id'], 1);
			$this->view->client_info = $client_info;
			
			$select = $dealers_db->select();
			$select->from("b_contract_dealer", array("dealer_id"));
			$select->where("contract_id = ?", $params['contract_id']);
			$rows = $dealers_db->fetchAll($select);
			
			$mod_statuses = new Db_Tables2_BDictContractStatus();
			$this->view->statuses = $mod_statuses->GetStatuses();
			
			$dealer_arr = array();
			$dealer_str = "";
			
			if($rows)
			{
				foreach($rows as $row)
				{
					$dealer_arr[] = $row['dealer_id'];
				}
			}
			
			if(!empty($dealer_arr))
			{
				$dealer_str = implode(", ", $dealer_arr);
			}
			
			$contract_info['dealers_str'] = $dealer_str;
			
			$this->view->contract_info = $contract_info;
			
			$sku_info = array(
				"base_info" => NULL,
				"service_info" => NULL
			);
			
			$select = $dealers_db->select();
			$select->from("b_contract_sku", "*");
			$select->where("contract_id = ?", $params['contract_id']);
			$sku_info['base_info'] = $dealers_db->fetchAll($select);
			
			$cs_id_arr = array();
			
			if($sku_info['base_info'])
			{
				$mod_sku = new Db_Tables2_BSku();
				
				foreach($sku_info['base_info'] as $id => $sinfo)
				{
					$sku_info['base_info'][$id]['sku_path'] = $mod_sku->GetSkuPath($sinfo['sku_id']);
					$cs_id_arr[] = $sinfo['cs_id'];
				}
				
				$mod_sku_service = new Db_Tables2_BContractSkuService();
				$sku_info['service_info'] = $mod_sku_service->GetServiceStr($cs_id_arr);
			}
			
			$this->view->sku_info = $sku_info;
			
			$mod_status = new Db_Tables2_BDictDeliveryStatus();
			$this->view->delivery_statuses = $mod_status->GetStatuses();
			
			//get log
			$select = $dealers_db->select();
			$select->from("b_logs_contract", "*");
			$select->where("contract_id = ?", $params['contract_id']);
			$select->order("lid DESC");
			$this->view->logs = $dealers_db->fetchAll($select);
			
			//get action log
			$mod_action_log = new Db_Tables2_BLogsAction();
			$this->view->action_logs = $mod_action_log->GetLogs(array(1), $params['contract_id']);
			
			if($params['msg'])
			{
					switch ($params['msg'])
					{
						case 1:
							$this->view->msg = "操作成功。";
							break;
						case 2:
							$this->view->msg = "操作失败。";
							break;
					}
			}
		}else{
			$this->_redirect("/contracts/index/msg/5");
		}
	}
	
	function editContractSubmitAction()
	{
		$params = $this->_request->getParams();
		
		if($params['contract_id'])
		{
			$dealers_db = Zend_Registry::get('dealers_db');
			
			$select = $dealers_db->select();
			$select->from("b_contract", "*");
			$select->where("contract_id = ?", $params['contract_id']);
			$row = $dealers_db->fetchRow($select);
			
			if($row)
			{
				$set = array(
					"receivable_value" => $row['contract_value'],
					"delivery_status" => $params['delivery_status']
				);
				
				//改为合同管理员权限 0327
//				if(!$row['sign_date'] && !$row['contract_sid'] && $params['launch_switcher'])
//				{
//					$ext = new Sys_Extensions();
//					$set['contract_sid'] = $ext->GenerateOrderSid();
//					$set['sign_date'] = date("Y-m-d");
//				}
				
				$where = "contract_id = ".$params['contract_id'];
				
				$dealers_db->update("b_contract", $set, $where);
				
				$this->_redirect("/contracts/edit-contract/contract_id/".$params['contract_id']."/msg/1");
			}else{
				$this->_redirect("/contracts/index/msg/6");
			}
		}else{
			echo "缺少关键参数";
			die;
		}
	}
	
	function addContractLogAction()
	{
		$params = $this->_request->getParams();
		
		if("LEVEL-4" == $_SESSION['identity']['level'] && $params['contract_id'])
		{
			$this->view->title = "添加认款记录";
			$this->view->contract_id = $params['contract_id'];
			
			$dealers_db = Zend_Registry::get('dealers_db');
			$select = $dealers_db->select();
			$select->from("b_contract", array("receivable_value", "received_value"));
			$select->where("contract_id = ?", $params['contract_id']);
			$row = $dealers_db->fetchRow($select);

			$this->view->remaining_value = $row['receivable_value'] - $row['received_value'];
			
			if(0 > $this->view->remaining_value)
			{
				$this->view->remaining_value = 0;
			}
			
			$select = $dealers_db->select();
			$select->from("b_contract_invoice", array("invoice_num"));
			$select->where("contract_id = ?", $params['contract_id']);
			$row = $dealers_db->fetchRow($select);
			
			$is_applied = 0;
			$invoice_num = NULL;
			
			if($row)
			{
				$is_applied = 1;
				
				if($row['invoice_num'])
				{
					$invoice_num = $row['invoice_num'];
				}
			}
			
			$this->view->is_applied = $is_applied;
			$this->view->invoice_num = $invoice_num;
		}else{
			echo "无此权限";
			die;
		}
	}
	
	function addContractLogSubmitAction()
	{
		$params = $this->_request->getParams();
		
		if($params['contract_id'] && is_numeric($params['avalue']) && $params['pay_date'] && "LEVEL-4" == $_SESSION['identity']['level'])
		{
			$ctime = $params['pay_date']." 12:00:00";
			
			$data = array(
				"contract_id" => $params['contract_id'],
				"value" => $params['avalue'],
				"emp_id" => $_SESSION['identity']['userid'],
				"ctime" => $ctime
			);
			
			if($params['invoice'])
			{
				$data['invoice'] = $params['invoice'];
			}
			
			if($params['tips'])
			{
				$data['tips'] = $params['tips'];
			}
			
			$dealers_db = Zend_Registry::get('dealers_db');
			
			if($dealers_db->insert("b_logs_contract", $data))
			{
				$select = $dealers_db->select();
				$select->from("b_contract", "*");
				$select->where("contract_id = ?", $params['contract_id']);
				$row = $dealers_db->fetchRow($select);
				
				$received_value = $row['received_value'] + $params['avalue'];
				
				//改为合同管理员权限 0327
//				$set = array();
//				
//				if($received_value >= $row['receivable_value'])
//				{
//					if(!$row['sign_date'] && !$row['contract_sid'])
//					{
//						$ext = new Sys_Extensions();
//						$set['contract_sid'] = $ext->GenerateOrderSid();
//						$set['sign_date'] = date("Y-m-d");
//					}
//				}
//				
//				if(!empty($set))
//				{
//					$where = "contract_id = ".$params['contract_id'];
//					$dealers_db->update("b_contract", $set, $where);
//				}
				
				//update contract value
				$mod_contract = new Db_Tables2_BContract();
				$mod_contract->UpdateContractValue($params['contract_id'], 1, $params['avalue']);
				
				if(!$row['launch_switcher'])
				{
					$mod_contract = new Db_Tables2_BContract();
					$mod_contract->LaunchSwitcher($params['contract_id'], 1, 2);
				}
				
				$this->_redirect("/contracts/edit-contract/contract_id/".$params['contract_id']."/msg/1");
			}else{
				$this->_redirect("/contracts/edit-contract/contract_id/".$params['contract_id']."/msg/2");
			}
		}else{
			echo "无此权限";
			die;
		}
	}
	
	function viewContractAction()
	{
		$params = $this->_request->getParams();
		$this->view->title = "查看合同";
		
		if($params['contract_id'])
		{
			$dealers_db = Zend_Registry::get('dealers_db');
			
			$select = $dealers_db->select();
			$select->from("b_contract as c", array(
				"contract_id",
				"contract_sid",
				"province_id",
				"province_name",
				"city_id",
				"city_name",
				"start_date",
				"expired_date",
				"sign_date",
				"sales_emp_id",
				"sales_emp_name",
				"client_id",
				"client_name",
				"signer_id",
				"signer_company_name",
				"owner_id",
				"owner_name",
				"contract_claim_amount",
				"contract_value",
				"contract_cost",
				"receivable_value",
				"received_value",
				"tips",
				"status",
				"launch_switcher",
				"ctime",
				"pay_type",
				"pay_date",
				"allow_edit",
                "sign_type"
			));
			$select->joinLeft("b_client_type as t", "t.client_type_id=c.client_type_id", array("name as client_type_name"));
			$select->joinLeft("b_dict_delivery_status as s", "s.ds_id=c.delivery_status", array("name as delivery_status_name"));
			$select->where("c.contract_id = ?", $params['contract_id']);
			$contract_info = $dealers_db->fetchRow($select);
			
			$mod_client = new Db_Tables2_BClient();
			$client_info = $mod_client->FetchClientDetail($contract_info['client_id'], 1);
			$this->view->client_info = $client_info;
			
			$select = $dealers_db->select();
			$select->from("b_contract_dealer", array("dealer_id"));
			$select->where("contract_id = ?", $params['contract_id']);
			$rows = $dealers_db->fetchAll($select);
			
			$dealer_arr = array();
			$dealer_str = "";
			
			if($rows)
			{
				foreach($rows as $row)
				{
					$dealer_arr[] = $row['dealer_id'];
				}
			}
			
			if(!empty($dealer_arr))
			{
				$dealer_str = implode(", ", $dealer_arr);
			}
			
			$contract_info['dealers_str'] = $dealer_str;
			
			$mod_approval = new Db_Tables2_BLogsSalesApproval();
			
			$next = $mod_approval->GetNext(2, $params['contract_id']);
			
			if(!empty($next))
			{
				$contract_info['next_leader_id'] = $next['emp_id'];
			}
			
			$this->view->contract_info = $contract_info;
			
			$sku_info = array(
				"base_info" => NULL,
				"service_info" => NULL
			);
			
			$select = $dealers_db->select();
			$select->from("b_contract_sku", "*");
			$select->where("contract_id = ?", $params['contract_id']);
			$sku_info['base_info'] = $dealers_db->fetchAll($select);
			
			$cs_id_arr = array();
			
			if($sku_info['base_info'])
			{
				$mod_sku = new Db_Tables2_BSku();
				
				foreach($sku_info['base_info'] as $id => $sinfo)
				{
					$sku_info['base_info'][$id]['sku_path'] = $mod_sku->GetSkuPath($sinfo['sku_id']);
					$cs_id_arr[] = $sinfo['cs_id'];
				}
				
				$mod_sku_service = new Db_Tables2_BContractSkuService();
				$sku_info['service_info'] = $mod_sku_service->GetServiceStr($cs_id_arr);
			}
			
			$this->view->sku_info = $sku_info;
			
			$mod_statuses = new Db_Tables2_BDictContractStatus();
			$this->view->statuses = $mod_statuses->GetStatuses();
			
			$mod_pay_plan = new Db_Tables2_BLogsContractPayPlan();
			$this->view->pay_plans = $mod_pay_plan->GetPayPlans($params['contract_id']);
			
			//get approval log
			$select = $dealers_db->select();
			$select->from("b_logs_contract_approval", "*");
			$select->where("contract_id = ?", $params['contract_id']);
			$select->order("lid DESC");
			$this->view->logs_approval = $dealers_db->fetchAll($select);
			
			//get action log
			$mod_action_log = new Db_Tables2_BLogsAction();
			$this->view->action_logs = $mod_action_log->GetLogs(array(1), $params['contract_id']);
			
			if($params['msg'])
			{
					switch ($params['msg'])
					{
						case 1:
							$this->view->msg = "操作成功。";
							break;
						case 2:
							$this->view->msg = "操作失败。";
							break;
						case 3:
							$this->view->msg = "驳回成功.";
							break;
						case 4:
							$this->view->msg = "您没有操作权限.";
							break;
					}
			}
		}else{
			$this->_redirect("/contracts/index/msg/5");
		}
	}
	
	function editContractType2Action()
	{

		$params = $this->_request->getParams();
//		$ext = new Sys_Extensions();
//		$ext->FormatArray($_SESSION['contract-edit-type2']);die;
//		unset($_SESSION['contract-edit-type2'][$params['contract_id']]);
		$this->view->contract_id = $params['contract_id'];
		$dealers_db = Zend_Registry::get('dealers_db');
		
		if($params['contract_id'] && !isset($_SESSION['contract-edit-type2'][$params['contract_id']]))
		{
			$select = $dealers_db->select();
			$select->from("b_contract as c", array(
				"contract_id",
				"contract_sid",
				"contract_type_id",
				"province_id",
				"province_name",
				"city_id",
				"city_name",
				"start_date",
				"expired_date",
				"sign_date",
				"sales_emp_id",
				"sales_emp_name",
				"client_id",
				"client_name",
				"signer_id",
				"signer_company_name",
				"owner_id",
				"owner_name",
				"contract_claim_amount",
				"contract_value",
				"contract_cost",
				"receivable_value",
				"received_value",
				"tips",
				"status",
				"launch_switcher",
				"ctime",
				"pay_type",
				"pay_date",
				"allow_edit",
				"sign_type",
				"invoice_type",
				"key_account_sales"
			));
			$select->joinLeft("b_client_type as t", "t.client_type_id=c.client_type_id", array("name as client_type_name"));
			$select->joinLeft("b_dict_delivery_status as s", "s.ds_id=c.delivery_status", array("name as delivery_status_name"));
			$select->where("c.contract_id = ?", $params['contract_id']);
			$contract_info = $dealers_db->fetchRow($select);
			$mod_client = new Db_Tables2_BClient();
			$client_info = $mod_client->FetchClientDetail($contract_info['client_id'], 1);
			$this->view->client_info = $client_info;

			$select = $dealers_db->select();
			$select->from("b_contract_dealer", array("dealer_id"));
			$select->where("contract_id = ?", $params['contract_id']);
			$rows = $dealers_db->fetchAll($select);
			$dealer_arr = array();
			$dealer_str = "";

			if($rows)
			{
				foreach($rows as $row)
				{
					$dealer_arr[] = $row['dealer_id'];
				}
			}

			if(!empty($dealer_arr))
			{
				$dealer_str = implode(", ", $dealer_arr);
			}

			$contract_info['dealers_str'] = $dealer_str;

			$this->view->contract_info = $contract_info;

			$select = $dealers_db->select();
			$select->from("b_contract_sku", "*");
			$select->where("contract_id = ?", $params['contract_id']);
			$sku_rows = $dealers_db->fetchAll($select);

			$sku_info = array();

			if(!empty($sku_rows))
			{
				foreach($sku_rows as $srow)
				{
					$sku_info_row = array(
						"sku_id" => $srow['sku_id'],
						"sku_quantity" => $srow['quantity'],
						"actual_pay" => $srow['actual_pay'],
						"start_date" => $srow['start_date'],
						"expired_date" => $srow['expired_date'],
						"hxb_account" => $srow['hxb_account'],
						"961_bonus" => $srow['961_discount'],
						"product_id" => $srow['product_id'],
						"dealer_id" => $srow['dealer_id'],
						"service_ids" => array()
					);
					
					$select = $dealers_db->select();
					$select->from("b_contract_sku_service", "*");
					$select->where("cs_id = ?", $srow['cs_id']);
					$service_rows = $dealers_db->fetchAll($select);

					if(!empty($service_rows))
					{
						foreach($service_rows as $vrow)
						{
							$sku_info_row['service_ids'][] = $vrow['service_id'];
							$sku_info_row['start_date_'.$vrow['service_id']] = $vrow['start_date'];
							$sku_info_row['expired_date_'.$vrow['service_id']] = $vrow['expired_date'];
						}
					}

					$sku_info[] = $sku_info_row;
				}
			}

			$this->view->title = "编辑合同 - ".$client_info['client_name'];
			
			if(!empty($client_info))
			{
				if(!isset($_SESSION['contract-edit-type2']))
				{
					$_SESSION['contract-edit-type2'] = array();
				}

				$_SESSION['contract-edit-type2'][$contract_info['contract_id']] = array(
					"client_info" => array(),
					"contract_info" => array(
						"contract_sid" => $contract_info['contract_sid']?$contract_info['contract_sid']:NULL,
						"contract_type_id" => $contract_info['contract_type_id'],
						"start_date" => $contract_info['start_date'],
						"expired_date" => $contract_info['expired_date'],
						"signer_id" => $contract_info['signer_id'],
						"signer_company_name" => $contract_info['signer_company_name'],
						"owner_id" => $contract_info['owner_id'],
						"owner_name" => $contract_info['owner_name'],
						"contract_claim_amount" => $contract_info['contract_claim_amount'],
						"contract_value" => $contract_info['contract_value'],
						"contract_cost" => $contract_info['contract_cost'],
						"tips" => $contract_info['tips'],
						"sign_date" => $contract_info["sign_date"],
						"sales_emp_id" => $contract_info['sales_emp_id'],
						"sales_emp_name" => $contract_info['sales_emp_name'],
						"dealers_arr" => array(),
						"dealers_str" => "",
						"pay_type" => $contract_info['pay_type'],
						"pay_date" => $contract_info['pay_date'],
						"sign_type" => $contract_info['sign_type'],
						"invoice_type" => $contract_info['invoice_type'],
						"key_account_sales" => $contract_info['key_account_sales']
					),
					"sku_info" => $sku_info
				);
				
				$ext = new Sys_Extensions();
				$ext->ReCalculateNewContract($contract_info['contract_id']);
				
				$_SESSION['contract-edit-type2'][$contract_info['contract_id']]['client_info'] = $client_info;
				
				$select = $dealers_db->select();
				$select->from("b_contract_dealer", "*");
				$select->where("contract_id = ?", $params['contract_id']);
				$contract_dealers = $dealers_db->fetchAll($select);

				if($contract_dealers)
				{
					$dealer_ids = array();
					
					foreach($contract_dealers as $contract_dealer)
					{
						$dealer_ids[] = $contract_dealer['dealer_id'];
						$_SESSION['contract-edit-type2'][$contract_info['contract_id']]['contract_info']['dealers_arr'][$contract_dealer['dealer_id']] = $contract_dealer['dealer_name'];
					}
					
					$_SESSION['contract-edit-type2'][$contract_info['contract_id']]['contract_info']['dealers_str'] = implode(", ", $dealer_ids);
				}

				$mod_signer = new Db_Tables2_BClientSigner();
				$this->view->signers = $mod_signer->GetClientSigner($contract_info['client_id']);

				$mod_owner = new Db_Tables2_BOwner();
				$this->view->owners = $mod_owner->GetOwners();

				$mod_params = new Db_Tables2_BDictParams();
				$sales_role_id = array();
				$sales_role_id[] = $mod_params->GetVal("LEVEL-1");
				$sales_role_id[] = $mod_params->GetVal("LEVEL-2");

				$mod_user = new Db_Tables2_User();
				$this->view->sales = $mod_user->GetUsersByRole($sales_role_id);
				
				$mod_pay_plan = new Db_Tables2_BLogsContractPayPlan();
				$_SESSION['contract-edit-type2'][$contract_info['contract_id']]['pay_plan'] = array();
				
				$pay_plans = $mod_pay_plan->GetPayPlans($params['contract_id']);
				
				if(is_array($pay_plans))
				{
					if(!empty($pay_plans))
					{
						foreach($pay_plans as $pay_plan)
						{
							$_SESSION['contract-edit-type2'][$contract_info['contract_id']]['pay_plan'][] = array(
								"plan_date" => $pay_plan['plan_date'],
								"plan_value" => $pay_plan['plan_value'],
								"tips" => $pay_plan['tips'],
								"invoice" => $pay_plan['invoice'],
								"status" => $pay_plan['status']
							);
						}
					}
				}
			}else{
				$this->_redirect("/contracts");
			}
		}elseif($_SESSION['contract-edit-type2'][$params['contract_id']]){

			$this->view->title = "编辑合同 - ".$_SESSION['contract-edit-type2'][$params['contract_id']]['client_info']['client_name'];

			$mod_signer = new Db_Tables2_BClientSigner();
			$this->view->signers = $mod_signer->GetClientSigner($_SESSION['contract-edit-type2'][$params['contract_id']]['client_info']['client_id']);

			$mod_owner = new Db_Tables2_BOwner();
			$this->view->owners = $mod_owner->GetOwners();

			$mod_params = new Db_Tables2_BDictParams();
			$sales_role_id = array();
			$sales_role_id[] = $mod_params->GetVal("LEVEL-1");
			$sales_role_id[] = $mod_params->GetVal("LEVEL-2");

			$mod_user = new Db_Tables2_User();
			$this->view->sales = $mod_user->GetUsersByRole($sales_role_id);
		}else{
			$this->_redirect("/contracts");
		}

		if($params['msg'])
		{
				switch ($params['msg'])
				{
					case 1:
						$this->view->msg = "新增产品成功";
						break;
					case 2:
						$this->view->msg = "新增产品失败";
						break;
				}
		}
	}
	
	function editContractType2SubmitAction()
	{
		$params = $this->_request->getParams();
//		$ext = new Sys_Extensions();
//		$ext->FormatArray($_SESSION['contract']);die;
		if($_SESSION['contract-edit-type2'][$params['contract_id']])
		{
			$data = array(
				"start_date" => $_SESSION['contract-edit-type2'][$params['contract_id']]['contract_info']['start_date'],
				"expired_date" => $_SESSION['contract-edit-type2'][$params['contract_id']]['contract_info']['expired_date'],
				"contract_claim_amount" => $_SESSION['contract-edit-type2'][$params['contract_id']]['contract_info']['contract_claim_amount'],
				"contract_value" => $_SESSION['contract-edit-type2'][$params['contract_id']]['contract_info']['contract_value'],
				"receivable_value" => $_SESSION['contract-edit-type2'][$params['contract_id']]['contract_info']['contract_value']-$_SESSION['contract-edit-type2'][$params['contract_id']]['contract_info']['contract_cost']
			);

			if(!in_array($_SESSION['identity']['level'], array("LEVEL-3", "LEVEL-4")))
			{
				$data['status'] = 0;
				$data['allow_edit'] = 0;
				$data['ctime'] = date("Y-m-d H:i:s");
			}

			//检查主表单是否改变

			//签约公司
			if(is_numeric($params['signer_id']))
			{
				if($params['signer_id'] != $_SESSION['contract-edit-type2'][$params['contract_id']]['contract_info']['signer_id'])
				{
					$mod_signer = new Db_Tables2_BSigner();
					$signer = $mod_signer->FetchSignerDetails($params['signer_id']);
					$signer_id = $params['signer_id'];
					$signer_company_name = $signer['company_name'];
				}else{
					$signer_id = $_SESSION['contract-edit-type2'][$params['contract_id']]['contract_info']['signer_id'];
					$signer_company_name = $_SESSION['contract-edit-type2'][$params['contract_id']]['contract_info']['signer_company_name'];
				}
			}else{
				$signer_id = NULL;
				$signer_company_name = NULL;
			}

			$data['signer_id'] = $signer_id;
			$data['signer_company_name'] = $signer_company_name;

			//乙方单位
			if(is_numeric($params['owner_id']))
			{
				if($params['owner_id'] != $_SESSION['contract-edit-type2'][$params['contract_id']]['contract_info']['owner_id'])
				{
					$mod_owner = new Db_Tables2_BOwner();
					$owner = $mod_owner->FetchOwnerDetails($params['owner_id']);
					$owner_id = $params['owner_id'];
					$owner_name = $owner['owner_name'];
				}else{
					$owner_id = $_SESSION['contract-edit-type2'][$params['contract_id']]['contract_info']['owner_id'];
					$owner_name = $_SESSION['contract-edit-type2'][$params['contract_id']]['contract_info']['owner_name'];
				}
			}else{
				$owner_id = NULL;
				$owner_name = NULL;
			}

			if($owner_id)
			{
				$data['owner_id'] = $owner_id;
				$data['owner_name'] = $owner_name;
			}

			//付款方式
			$data['pay_type'] = $params['pay_type'];

			if(2 == $params['pay_type'])
			{
				$data['pay_date'] = $params['pay_date'];
			}else{
				$data['pay_date'] = NULL;
			}

			//签约类型
			$data['sign_type'] = $params['sign_type'];

			if(2 == $params['sign_type'])
			{
				$data['key_account_sales'] = $params['key_account_sales'];
			}else{
				$data['key_account_sales'] = NULL;
			}

			//备注
			if($params['tips'])
			{
				$data['tips'] = $params['tips'];
			}else{
				$data['tips'] = NULL;
			}

			$mod_user = new Db_Tables2_User();
			$my_leader = $mod_user->GetMyLeaders($_SESSION['contract-edit-type2'][$params['contract_id']]['contract_info']['sales_emp_id']);

			//approved automatically
			if(empty($my_leader))
			{
				$data['status'] = 1;
			}

			$contract_id = $params['contract_id'];
			$contract_status = $data['status'];

			$dealers_db = Zend_Registry::get('dealers_db');
			$where = "contract_id=".$contract_id;
			$dealers_db->update("b_contract", $data, $where);

			if($contract_id)
			{
				//add approval log
				if(!$contract_status && !in_array($_SESSION['identity']['level'], array("LEVEL-3", "LEVEL-4")))
				{
					//删除旧数据
					$where = "type=2 and target_id=".$contract_id;
					$dealers_db->delete("b_logs_sales_approval", $where);
					
					//车智推先由孟居洲审
					//百度有驾也一样 2020.5.13
					$czt_product_id = 2;
					$bdyj_product_id = 14;
					
					$is_czt_contract = 0;
					
					$mod_skus = new Db_Tables2_BSku();
					
					if(!empty($_SESSION['contract-edit-type2'][$params['contract_id']]['sku_info']))
					{
						foreach($_SESSION['contract-edit-type2'][$params['contract_id']]['sku_info'] as $sku_info)
						{
							$si = $mod_skus->GetSkuRow($sku_info['sku_id']);
							
							if($si['product_id'] == $czt_product_id || $si['product_id'] == $bdyj_product_id)
							{
								$is_czt_contract = 1;
								break;
							}
						}
					}
					
					if($is_czt_contract)
					{
						$set = array(
							"type" => 2,
							"target_id" => $contract_id,
							"emp_id" => 626,
							"emp_name" => '孟居洲',
							"status" => 0
						);

						$dealers_db->insert("b_logs_sales_approval", $set);
					}

					//添加主管审批记录
					$leaders_arr = $mod_user->GetMyLeaders($_SESSION['contract-edit-type2'][$params['contract_id']]['contract_info']['sales_emp_id']);

					if(!empty($leaders_arr))
					{
						foreach($leaders_arr as $leader)
						{
							$set = array(
								"type" => 2,
								"target_id" => $contract_id,
								"emp_id" => $leader['emp_id'],
								"emp_name" => $leader['emp_name'],
								"status" => 0
							);

							$dealers_db->insert("b_logs_sales_approval", $set);
						}
					}
				}

				//del
				$where = "contract_id=".$contract_id;
				$dealers_db->delete("b_contract_dealer", $where);

				//insert other info
				if(!empty($_SESSION['contract-edit-type2'][$params['contract_id']]['contract_info']['dealers_arr']))
				{
					foreach($_SESSION['contract-edit-type2'][$params['contract_id']]['contract_info']['dealers_arr'] as $dealer_id => $dealer_name)
					{
						$data = array(
							"contract_id" => $contract_id,
							"dealer_id" => $dealer_id,
							"dealer_name" => $dealer_name
						);

						$dealers_db->insert("b_contract_dealer", $data);
					}
				}

				//del
				$where = "contract_id=".$contract_id;
				$dealers_db->delete("b_contract_sku", $where);
				$dealers_db->delete("b_contract_sku_service", $where);

				if(!empty($_SESSION['contract-edit-type2'][$params['contract_id']]['sku_info']))
				{
					$mod_sku = new Db_Tables2_BSku();

					$lp = 0;

					foreach($_SESSION['contract-edit-type2'][$params['contract_id']]['sku_info'] as $sku_info)
					{
						$mail_token = sha1($contract_id.$lp);
						$lp += 1;

						$product_sku = $mod_sku->GetSkuRow($sku_info['sku_id']);

						$data = array(
							"contract_id" => $contract_id,
							"product_id" => $product_sku['product_id'],
							"product_name" => $product_sku['product_name'],
							"sku_id" => $sku_info['sku_id'],
							"sku_name" => $product_sku['sku_name'],
							"unit_name" => $product_sku['unit_name'],
							"unit_price" => $sku_info['unit_price'],
							"quantity" => $sku_info['sku_quantity'],
							"rrp" => $sku_info['unit_price'] * $sku_info['sku_quantity'],
							"claim_amount" => $sku_info['unit_price'] * $sku_info['sku_quantity'] / 2,
							"actual_pay" => $sku_info['actual_pay'],
							"start_date" => $sku_info['start_date'],
							"expired_date" => $sku_info['expired_date'],
							"mail_token" => $mail_token,
							"dealer_id" => $sku_info['dealer_id'],
                            "hxb_account" => $sku_info['hxb_account'],
                            "961_discount" => $sku_info['961_bonus']

                        );

						if($dealers_db->insert("b_contract_sku", $data))
						{
							if(!empty($sku_info['service_ids']))
							{
								$select = $dealers_db->select();
								$select->from("b_contract_sku", "cs_id");
								$select->order("cs_id DESC");
								$row = $dealers_db->fetchRow($select);

								if($row)
								{
									$cs_id = $row['cs_id'];
								}

								if($cs_id)
								{
									$mod_service = new Db_Tables2_BDictService();
									$services = $mod_service->GetServices();

									foreach($sku_info['service_ids'] as $service_id)
									{
										$data = array(
											"contract_id" => $contract_id,
											"cs_id" => $cs_id,
											"service_id" => $service_id,
											"service_name" => $services[$service_id],
											"start_date" => $sku_info['start_date_'.$service_id],
											"expired_date" => $sku_info['expired_date_'.$service_id]
										);

										$dealers_db->insert("b_contract_sku_service", $data);
									}
								}
							}
						}
					}
				}
				
				$where = "contract_id=".$contract_id." and status=0";
				$dealers_db->delete("b_logs_contract_pay_plan", $where);
				
				if($_SESSION['contract-edit-type2'][$contract_id]['pay_plan'])
				{
					$ctime = date("Y-m-d H:i:s");
					
					foreach($_SESSION['contract-edit-type2'][$contract_id]['pay_plan'] as $val)
					{
						if(!$val['status'])
						{
							$data = array(
								"contract_id" => $contract_id,
								"plan_date" => $val['plan_date'],
								"plan_value" => $val['plan_value'],
								"tips" => $val['tips'],
								"status" => 0,
								"ctime" => $ctime
							);

							$dealers_db->insert("b_logs_contract_pay_plan", $data);
						}
					}
				}

				unset($_SESSION['contract-edit-type2'][$params['contract_id']]);

				$this->_redirect("/contracts/index/msg/7");
			}else{
				$this->_redirect("/contracts/edit-contract-type2/contract_id/".$contract_id."/error/2"); //关键参数缺失
			}
		}else{
			$this->_redirect("/contracts/edit-contract-type2/contract_id/".$contract_id."/error/1"); //关键参数缺失
		}
	}
	
	function rejectionAction()
	{
		$params = $this->_request->getParams();
		$this->view->title = "驳回合同";
		
		if($params['contract_id'])
		{
			$dealers_db = Zend_Registry::get('dealers_db');
			
			$select = $dealers_db->select();
			$select->from("b_contract as c", array("ctime", "sales_emp_name", "client_name", "contract_id"));
			$select->where("c.contract_id = ?", $params['contract_id']);
			$this->view->data = $dealers_db->fetchRow($select);
		}
	}
	
	function rejectionSubmitAction()
	{
		$params = $this->_request->getParams();
		
		if($params['contract_id'])
		{
			$mod_rejection = new Db_Tables2_BContractRejection();
			$mod_rejection->contract_id = $params['contract_id'];
			$mod_rejection->reason = trim($params['reason']);
			$mod_rejection->AddRecord();
            $mailList = new Db_Tables2_BMailList();
            $mailList->SendServiceNotificationToSales($params['contract_id']);
			
			//写入审批日志
			$mod_logs_approval = new Db_Tables2_BLogsContractApproval();
			$mod_logs_approval->AddRecord($params['contract_id'], $_SESSION['identity']['userid'], $_SESSION['identity']['realname'], 98, trim($params['reason']));

			$this->_redirect("/contracts/view-contract/contract_id/".$params['contract_id']."/msg/3");
		}else{
			$this->_redirect("/contracts"); //关键参数缺失
		}
	}
	
	function addBaseContractAction()
	{
		$params = $this->_request->getParams();
		
		if($params['contract_id'])
		{
			$dealers_db = Zend_Registry::get('dealers_db');
			$select = $dealers_db->select();
			$select->from("b_contract", array("client_id", "contract_id", "contract_sid", "contract_type_id", "signer_id", "owner_id", "pay_type", "sign_type"));
			$select->where("contract_id = ?", $params['contract_id']);
			$row = $dealers_db->fetchRow($select);
			
			if($row)
			{
				if($row['contract_sid'])
				{
					$contract_sid = $row['contract_sid'];
				}else{
					$contract_sid = 0;
				}
				
				$this->_redirect("/contracts/add-contract-step2/client_id/".$row['client_id']."/contract_type_id/".$row['contract_type_id']."/parent_contract_id/".$row['contract_id']."/parent_contract_sid/".$contract_sid."/signer_id/".$row['signer_id']."/owner_id/".$row['owner_id']."/pay_type/".$row['pay_type']."/sign_type/".$row['sign_type']);
			}else{
				$this->_redirect("/contracts"); //关键参数缺失
			}
		}else{
			$this->_redirect("/contracts"); //关键参数缺失
		}
	}
	
	function invoiceApplyAction()
	{
		$params = $this->_request->getParams();
		$this->view->title = "开票申请";
		
		if($params['contract_id'] && $_SESSION['identity']['userid'])
		{
			$dealers_db = Zend_Registry::get('dealers_db');
			$select = $dealers_db->select();
			$select->from("b_contract as c", array("contract_id", "contract_sid", "client_name", "invoice_type", "invoice_done", "sales_emp_id", "signer_id"));
			$select->joinLeft("b_signer as s", "s.signer_id=c.signer_id", array("company_name", "contact_name", "contact_address", "tel", "register_address", "business_number", "tax_number", "bank_name", "bank_number", "is_regular_taxpayer", "img1", "img3", "img4"));
			$select->where("c.contract_id = ?", $params['contract_id']);
			$row = $dealers_db->fetchRow($select);
			
			if($row)
			{
				if($row['contract_sid'] && 2 != $row['invoice_done'])
				{
					if($_SESSION['identity']['userid'] == $row['sales_emp_id'] || "LEVEL-4" == $_SESSION['identity']['level'])
					{
						$result = array(
							"contract_id" => $row['contract_id'],
							"contract_sid" => $row['contract_sid'],
							"signer_id" => $row['signer_id'],
							"client_name" => $row['client_name'],
							"invoice_type" => $row['invoice_type'],
							"invoice_applying" => $row['invoice_applying'],
							"company_name" => $row['company_name'],
							"tax_number" => $row['tax_number'],
							"register_address" => $row['register_address'],
							"bank_name" => $row['bank_name'],
							"bank_number" => $row['bank_number'],
							"contact_name" => $row['contact_name'],
							"tel" => $row['tel'],
							"contact_address" => $row['contact_address'],
							"img1" => $row['img1'],
							"img3" => $row['img3'],
							"img4" => $row['img4']
						);
						
						$this->view->data = $result;
						
						$select = $dealers_db->select();
						$select->from("b_contract_sku", "*");
						$select->where("contract_id = ?", $params['contract_id']);
						$rows = $dealers_db->fetchAll($select);
						
						$this->view->skus = $rows;
						
						$mod_invoice_name = new Db_Tables2_BDictProductInvoiceName();
						$this->view->invoice_names = $mod_invoice_name->MakeArr();

						$mod_invoice_version = new Db_Tables2_BDictProductInvoiceVersion();
						$this->view->invoice_versions = $mod_invoice_version->MakeArr();
						
						$this->view->stype = 0;
						
						if($params['type'])
						{
							$this->view->stype = $params['type'];
						}
					}else{
						$this->_redirect("/contracts/index/msg/9"); //必须合同发起人才可以开票
					}
				}else{
					$this->_redirect("/contracts/index/msg/8"); //该合同不满足开票标准
				}
			}else{
				$this->_redirect("/contracts/index/msg/6"); //找不到合同
			}
		}else{
			$this->_redirect("/contracts/index/msg/4"); //关键参数缺失
		}
	}
	
	function invoiceApplySubmitAction()
	{
		$params = $this->_request->getParams();
		
		$dealers_db = Zend_Registry::get('dealers_db');
		
		if($params['contract_id'])
		{
			//处理签约公司，如有，更新。无没有，创建
			$set = array(
				"company_name" => $params['company_name'],
				"tax_number" => $params['tax_number'],
				"register_address" => $params['register_address'],
				"bank_name" => $params['bank_name'],
				"bank_number" => $params['bank_number'],
				"contact_name" => $params['contact_name'],
				"tel" => $params['tel'],
				"contact_address" => $params['contact_address'],
				"emp_id" => $_SESSION['identity']['userid'],
				"status" => 1
			);
			
			if($params['signer_id']) //已有签约公司，更新
			{
				$where = "signer_id = ".$params['signer_id'];
				
				$dealers_db->update("b_signer", $set, $where);
				
				$signer_id = $params['signer_id'];
			}else{ //无签约公司，创建
				$set['ctime'] = date("Y-m-d H:i:s");
				
				if($dealers_db->insert("b_signer", $set))
				{
					$select = $dealers_db->select();
					$select->from("b_signer", "signer_id");
					$select->order("signer_id DESC");
					$row = $dealers_db->fetchRow($select);

					if($row)
					{
						$signer_id = $row['signer_id'];
					}
					
					//绑定客户和签约公司关系
					$select = $dealers_db->select();
					$select->from("b_contract", "client_id");
					$select->where("contract_id = ?", $params['contract_id']);
					$row = $dealers_db->fetchRow($select);
					
					if($row)
					{
						$set2 = array(
							"client_id" => $row['client_id'],
							"signer_id" => $signer_id,
							"status" => 1,
							"tips" => "K"
						);
						
						$dealers_db->insert("b_client_signer", $set2);
					}
				}
			}
			
			$img1_filename = $img3_filename = $img4_filename = "";
			
			if($_FILES['img1'])
			{
				$image = "img1-".$signer_id;

				if('image/jpeg' == $_FILES['img1']['type'])
				{
					$file_name = $image.".jpg";
				}elseif('image/png' == $_FILES['img1']['type'])
				{
					$file_name = $image.".png";
				}else{
					$file_name = NULL;
				}

				$file_folder = "upload/signers/";

				if($file_name)
				{
					move_uploaded_file($_FILES['img1']['tmp_name'], $file_folder.$file_name);
					$set['img1'] = $img1_filename = $file_name;
				}
			}else{
				$img1_filename = $params['old_img1'];
			}
			
			if($_FILES['img3'])
			{
				$image = "img3-".$signer_id;

				if('image/jpeg' == $_FILES['img3']['type'])
				{
					$file_name = $image.".jpg";
				}elseif('image/png' == $_FILES['img3']['type'])
				{
					$file_name = $image.".png";
				}else{
					$file_name = NULL;
				}

				$file_folder = "upload/signers/";

				if($file_name)
				{
					move_uploaded_file($_FILES['img3']['tmp_name'], $file_folder.$file_name);
					$set['img3'] = $img3_filename = $file_name;
				}
			}else{
				$img3_filename = $params['old_img3'];
			}
			
			if($_FILES['img4'])
			{
				$image = "img4-".$signer_id;

				if('image/jpeg' == $_FILES['img4']['type'])
				{
					$file_name = $image.".jpg";
				}elseif('image/png' == $_FILES['img4']['type'])
				{
					$file_name = $image.".png";
				}else{
					$file_name = NULL;
				}

				$file_folder = "upload/signers/";

				if($file_name)
				{
					move_uploaded_file($_FILES['img4']['tmp_name'], $file_folder.$file_name);
					$set['img4'] = $img4_filename = $file_name;
				}
			}else{
				$img4_filename = $params['old_img4'];
			}
			
			if($signer_id)
			{
				$set = array();
				
				if($img1_filename)
				{
					$set['img1'] = $img1_filename;
				}
				
				if($img3_filename)
				{
					$set['img3'] = $img3_filename;
				}
				
				if($img4_filename)
				{
					$set['img4'] = $img4_filename;
				}
				
				if(!empty($set))
				{
					$where = "signer_id = ".$signer_id;
					$dealers_db->update("b_signer", $set, $where);
				}
			}
			
			$select = $dealers_db->select();
			$select->from("b_signer", array("img1", "img3", "img4"));
			$select->where("signer_id = ?", $signer_id);
			$sirow = $dealers_db->fetchRow($select);
			
			//创建发票申请记录
			$set = array(
				"contract_id" => $params['contract_id'],
				"contract_sid" => $params['contract_sid'],
				"invoice_type" => $params['invoice_type'],
				"company_name" => $params['company_name'],
				"tax_number" => $params['tax_number'],
				"register_address" => $params['register_address'],
				"bank_name" => $params['bank_name'],
				"bank_number" => $params['bank_number'],
				"contact_name" => $params['contact_name'],
				"tel" => $params['tel'],
				"contact_address" => $params['contact_address'],
				"sales_emp_id" => $_SESSION['identity']['userid'],
				"sales_emp_name" => $_SESSION['identity']['realname'],
				"status" => 1, //申请中
				"ctime" => date("Y-m-d H:i:s")
			);
			
			if($img1_filename)
			{
				$set['img1'] = $img1_filename;
			}else{
				$set['img1'] = $sirow['img1'];
			}

			if($img3_filename)
			{
				$set['img3'] = $img3_filename;
			}else{
				$set['img3'] = $sirow['img3'];
			}

			if($img4_filename)
			{
				$set['img4'] = $img4_filename;
			}else{
				$set['img4'] = $sirow['img4'];
			}
			
			if($dealers_db->insert("b_contract_invoice", $set))
			{
				$select = $dealers_db->select();
				$select->from("b_contract_invoice", "id");
				$select->order("id DESC");
				$row = $dealers_db->fetchRow($select);

				if($row)
				{
					$invoice_id = $row['id'];
					
					$cs_ids = array();
					
					foreach($params as $pkey => $pval)
					{
						$ex = explode("sku_invoice_name_", $pkey);
						
						if(2 == count($ex))
						{
							$cs_ids[] = $ex[1];
						}
					}
					
					if(!empty($cs_ids))
					{
						$mod_contracts_sku = new Db_Tables2_BContractSku();
						
						foreach($cs_ids as $cs_id)
						{
							$set = array(
								"invoice_id" => $invoice_id,
								"cs_id" => $cs_id,
								"product_name" => $params['product_name_'.$cs_id],
								"sku_invoice_name" => $params['sku_invoice_name_'.$cs_id],
								"sku_invoice_version" => $params['sku_invoice_version_'.$cs_id],
								"quantity" => $params['quantity_'.$cs_id],
								"actual_pay" => $params['actual_pay_'.$cs_id],
								"apply_value" => $params['apply_value_'.$cs_id]
							);
							
							$dealers_db->insert("b_contract_invoice_sku", $set);
							
							$sku_update_result = $mod_contracts_sku->UpdateInvoiceApplied($cs_id, 1, $params['apply_value_'.$cs_id]);
						}
						
						if(isset($sku_update_result))
						{
							if($sku_update_result['result'] && $sku_update_result['contract_id'] && -1 != $sku_update_result['invoice_done'])
							{
								$set = array("invoice_done" => $sku_update_result['invoice_done']);
								$where = "contract_id=".$sku_update_result['contract_id'];
								$dealers_db->update("b_contract", $set, $where);
							}
						}
					}
				}
				
				//补充合同的签约公司关系
				$set = array(
					"invoice_type" => $params['invoice_type'],
					"signer_id" => $signer_id,
					"signer_company_name" => $params['company_name']
				);
				$where = "contract_id = ".$params['contract_id'];
				$dealers_db->update("b_contract", $set, $where);
				
				if(2 == $params['stype'])
				{
					$this->_redirect("/contracts/add-contract-log/contract_id/".$params['contract_id']);
				}else{
					$this->_redirect("/contracts/index/msg/11"); //开票成功
				}
			}else{
				$this->_redirect("/contracts/index/msg/10"); //异常原因失败
			}
		}else{
			$this->_redirect("/contracts/index/msg/4"); //关键参数缺失
		}
	}
	
    function invoicesAction()
    {
		$params = $this->_request->getParams();
		
		$this->view->title = "开票进度查询";
		
		$params_pool = array();
		$mod_tables = new Db_Joins_TablesJoins();
    	
		if($params['status'] && !empty($params['status']))
    	{
			$status_str = implode("_", $params['status']);
    		$mod_tables->status_str = $status_str;
    		$this->view->status_str = $status_str;
    		$params_pool[] = "status_str=".$status_str;
			$this->view->status = $params['status'];
    	}elseif($params['status_str'])
		{
			$status = explode("_", $params['status_str']);
    		$mod_tables->status_str = $params['status_str'];
    		$this->view->status_str = $params['status_str'];
    		$params_pool[] = "status_str=".$params['status_str'];
			$this->view->status = $status;
		}
		
		if(!in_array($_SESSION['identity']['level'], array("LEVEL-3", "LEVEL-4"))) //合同管理员和财务可以看所有，其他人只能看自己
		{
			$mod_tables->sales_emp_id = $_SESSION['identity']['userid'];
		}
		
		if($params['keyword'])
    	{
    		$mod_tables->keyword = $params['keyword'];
    		$this->view->keyword = $params['keyword'];
    		$params_pool[] = "keyword=".$params['keyword'];
    	}
		
		if(!$params['page_id'])
    	{
    		$page_id = 1;
    	}else{
    		$page_id = $params['page_id'];
    	}
    	
    	if($page_id)
    	{
    		$mod_tables->page_id = $page_id;
    		$this->view->page_id = $page_id;
    	}
		
		$this->view->data = $result = $mod_tables->GetInvoices();
		
		//make pagination
    	if(!empty($params_pool))
    	{
    		$params_string = implode("&", $params_pool);
    	}else{
    		$params_string = "";
    	}
    	
    	if(1 == $page_id)
    	{
    		$first_page_string = "";
    		$previous_page_string = "";
    	}else{
    		$first_page_string = "<a href='?page_id=1&".$params_string."'>最前页</a>&nbsp;&nbsp;&nbsp;";
    		$previous_page_string = "<a href='?page_id=".($page_id-1)."&".$params_string."'>上一页</a>&nbsp;&nbsp;&nbsp;";
    	}
    	
    	if($page_id < $result['total_pages'] )
    	{
    		$next_page_string = "<a href='?page_id=".($page_id+1)."&".$params_string."'>下一页</a>&nbsp;&nbsp;&nbsp;";
    		$last_page_string = "<a href='?page_id=".$result['total_pages']."&".$params_string."'>最后页</a>&nbsp;&nbsp;&nbsp;";
    	}else{
    		$next_page_string = "";
    		$last_page_string = "";
    	}
    	
		$this->view->params_string = $params_string;
    	$this->view->pagination = $first_page_string.$previous_page_string.$next_page_string.$last_page_string;
		
		if($params['status'])
		{
				switch ($params['status'])
				{
					case 1:
						$this->view->msg = "您已成功添加签约公司。";
						break;
					case 2:
						$this->view->msg = "状态更改成功";
						break;
					case 3:
						$this->view->msg = "状态更改失败";
						break;
					case 4:
						$this->view->msg = "更改成功";
						break;
				}
		}
	}
	
	function invoiceEditAction()
	{
		$params = $this->_request->getParams();
		$this->view->title = "开票申请审核";
		
		if($params['id'] && 'LEVEL-4' == $_SESSION['identity']['level'])
		{
			$dealers_db = Zend_Registry::get('dealers_db');
			$select = $dealers_db->select();
			$select->from("b_contract_invoice", "*");
			$select->where("id = ?", $params['id']);
			$row = $dealers_db->fetchRow($select);
			
			if($row)
			{
				$this->view->data = $row;
				
				$select = $dealers_db->select();
				$select->from("b_contract_invoice_sku", "*");
				$select->where("invoice_id = ?", $params['id']);
				$rows = $dealers_db->fetchAll($select);
				
				$this->view->skus = $rows;
				
				$mod_invoice_name = new Db_Tables2_BDictProductInvoiceName();
				$this->view->invoice_names = $mod_invoice_name->MakeArr();
				$this->view->invoice_names_arr = $mod_invoice_name->FetchAll();

				$mod_invoice_version = new Db_Tables2_BDictProductInvoiceVersion();
				$this->view->invoice_versions = $mod_invoice_version->MakeArr();
				$this->view->invoice_versions_arr = $mod_invoice_version->FetchAll();
				
				$mod_carriers = new Db_Tables2_BDictCarrier();
				$this->view->carriers = $mod_carriers->GetCarriers();
			}else{
				$this->_redirect("/contracts/index/msg/12"); //找不到开票申请
			}
		}else{
			$this->_redirect("/contracts/index/msg/4"); //关键参数缺失
		}
	}
	
	function invoiceEditSubmitAction()
	{
		$params = $this->_request->getParams();
		
		$dealers_db = Zend_Registry::get('dealers_db');
		
		if($params['invoice_id'])
		{
			$select = $dealers_db->select();
			$select->from("b_contract_invoice", "*");
			$select->where("id = ?", $params['invoice_id']);
			$invoice_row = $dealers_db->fetchRow($select);
			
			$set = array();
			
			if($params['status'])
			{
				$set['status'] = $params['status'];
				
				if(2 == $params['status'] && 2 != $invoice_row['status'])
				{
					$set['end_time'] = date("Y-m-d H:i:s");
				}
			}
			
			if($params['invoice_num'])
			{
				$set['invoice_num'] = $params['invoice_num'];
			}
			
			if($params['carrier_id'])
			{
				$set['carrier_id'] = $params['carrier_id'];
				
				$mod_carriers = new Db_Tables2_BDictCarrier();
				$carriers = $mod_carriers->GetCarriers();
				
				$set['carrier_name'] = $carriers[$params['carrier_id']];
			}
			
			if($params['carrier_tracking_num'])
			{
				$set['carrier_tracking_num'] = $params['carrier_tracking_num'];
			}
			
			$where = "id = ".$params['invoice_id'];
			$dealers_db->update("b_contract_invoice", $set, $where);
			
			$set2 = array();
			$mod_contract_sku = new Db_Tables2_BContractSku();
			
			if(2 == $params['status']) //审核通过
			{
				$refresh_result = $mod_contract_sku->RefreshInvoiceDone($invoice_row['contract_id']);

				if($refresh_result['result'])
				{
					$set2['invoice_done'] = $refresh_result['invoice_done'];
				}
			}elseif(3 == $params['status']) //驳回
			{
				$select = $dealers_db->select();
				$select->from("b_contract_invoice_sku", array("cs_id", "apply_value"));
				$select->where("invoice_id = ?", $params['invoice_id']);
				$invoice_sku_rows = $dealers_db->fetchAll($select);
				
				if(!empty($invoice_sku_rows))
				{
					foreach($invoice_sku_rows as $invoice_sku_row)
					{
						$update_result = $mod_contract_sku->UpdateInvoiceApplied($invoice_sku_row['cs_id'], 2, $invoice_sku_row['apply_value']);
					}
				}
				
				if($update_result['result'])
				{
					$set2['invoice_done'] = $update_result['invoice_done'];
				}
			}
			
			if(!empty($set2))
			{
				$where = "contract_id = ".$invoice_row['contract_id'];
				$dealers_db->update("b_contract", $set2, $where);
			}
			
			$this->_redirect("/contracts/invoices/msg/2");
		}else{
			$this->_redirect("/contracts/invoices/msg/3"); //关键参数缺失
		}
	}
	
	function editPayPlansAction()
	{
		$params = $this->_request->getParams();
		
		$this->view->contract_id = $params['contract_id'];
		$this->view->title = "编辑回款计划 - 合同ID: ".$params['contract_id'];
		
		$dealers_db = Zend_Registry::get('dealers_db');
		
		if($params['contract_id'])
		{
			$select = $dealers_db->select();
			$select->from("b_contract as c", array("sales_emp_id", "contract_value"));
			$select->where("c.contract_id = ?", $params['contract_id']);
			$contract_info = $dealers_db->fetchRow($select);
			
			$this->view->contract_info = $contract_info;
			
			if($contract_info['sales_emp_id'] == $_SESSION['identity']['userid'])
			{
				if(!isset($_SESSION['edit-pay-plans'][$params['contract_id']]))
				{
					$mod_pay_plan = new Db_Tables2_BLogsContractPayPlan();
					$_SESSION['edit-pay-plans'][$params['contract_id']] = array();

					$pay_plans = $mod_pay_plan->GetPayPlans($params['contract_id']);

					if(is_array($pay_plans))
					{
						if(!empty($pay_plans))
						{
							foreach($pay_plans as $pay_plan)
							{
								$_SESSION['edit-pay-plans'][$params['contract_id']][] = array(
									"plan_date" => $pay_plan['plan_date'],
									"plan_value" => $pay_plan['plan_value'],
									"tips" => $pay_plan['tips'],
									"invoice" => $pay_plan['invoice'],
									"status" => $pay_plan['status'],
									"confirmed_time" => $pay_plan['confirmed_time']
								);
							}
						}
					}
				}
			}else{
				$this->_redirect("/contracts/view-contract/contract_id/".$params['contract_id']."/msg/4");
			}
		}else{
			$this->_redirect("/contracts/view-contract/contract_id/".$params['contract_id']."/msg/4");
		}
	}
	
	function editPayPlansSubmitAction()
	{
		$params = $this->_request->getParams();
//		$ext = new Sys_Extensions();
//		$ext->FormatArray($_SESSION['contract']);die;
		if($_SESSION['edit-pay-plans'] && $params['contract_id'])
		{
			$dealers_db = Zend_Registry::get('dealers_db');
			$contract_id = $params['contract_id'];
				
			$where = "contract_id=".$contract_id;
			$dealers_db->delete("b_logs_contract_pay_plan", $where);

			if($_SESSION['edit-pay-plans'][$contract_id])
			{
				$ctime = date("Y-m-d H:i:s");

				foreach($_SESSION['edit-pay-plans'][$contract_id] as $val)
				{
					$data = array(
						"contract_id" => $contract_id,
						"plan_date" => $val['plan_date'],
						"plan_value" => $val['plan_value'],
						"tips" => $val['tips'],
						"ctime" => $ctime
					);
					
					if($val['status'])
					{
						$data['status'] = 1;
						$data['confirmed_time'] = $val['confirmed_time'];
					}else{
						$data['status'] = 0;
					}

					$dealers_db->insert("b_logs_contract_pay_plan", $data);
				}
			}

			unset($_SESSION['edit-pay-plans'][$contract_id]);

			$this->_redirect("/contracts/view-contract/contract_id/".$contract_id."/msg/1");
		}else{
			$this->_redirect("/contracts/view-contract/contract_id/".$contract_id."/msg/4");
		}
	}
	
	function payPlanActionAction()
	{
		$params = $this->_request->getParams();
		$this->view->title = "更新回款记录";
		
		if($params['plan_id'] && "LEVEL-4" == $_SESSION['identity']['level'])
		{
			$dealers_db = Zend_Registry::get('dealers_db');
			$select = $dealers_db->select();
			$select->from("b_logs_contract_pay_plan", "*");
			$select->where("plan_id = ?", $params['plan_id']);
			$this->view->data = $dealers_db->fetchRow($select);
		}else{
			$this->_redirect("/contracts/view-contract/contract_id/".$params['contract_id']."/msg/4");
		}
	}
	
	function payPlanActionSubmitAction()
	{
		$params = $this->_request->getParams();
		
		if($params['plan_id'])
		{
			$dealers_db = Zend_Registry::get('dealers_db');
			$select = $dealers_db->select();
			$select->from("b_logs_contract_pay_plan", "*");
			$select->where("plan_id = ?", $params['plan_id']);
			$data = $dealers_db->fetchRow($select);
			
			$set = array(
				"emp_id" => $_SESSION['identity']['userid'],
				"status" => 1,
				"confirmed_time" => date("Y-m-d H:i:s")
			);
			
			$where = "plan_id=".$params['plan_id'];
			
			$dealers_db->update("b_logs_contract_pay_plan", $set, $where);
			
			$select = $dealers_db->select();
			$select->from("b_contract", "*");
			$select->where("contract_id = ?", $data['contract_id']);
			$row = $dealers_db->fetchRow($select);

			$received_value = $row['received_value'] + $data['plan_value'];

			//update contract value
			$mod_contract = new Db_Tables2_BContract();
			$mod_contract->UpdateContractValue($data['contract_id'], 1, $data['plan_value']);

			if(!$row['launch_switcher'])
			{
				$mod_contract = new Db_Tables2_BContract();
				$mod_contract->LaunchSwitcher($data['contract_id'], 1, 2);
			}
			
			$this->_redirect("/contracts/view-contract/contract_id/".$data['contract_id']."#pay-plan");
		}else{
			echo "关键参数缺失";
			die;
		}
	}
}